C#面向对象22 委托事件反射
1.委托的定义:声明委托类型(返回值和参数,命名空间中);定义委托对象
(把委托想象成函数中的占位符~因为你并不确定调用哪个函数~)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace @delegate
{
public delegate void DelSayHi(string name);
class Program
{
static void Main(string[] args)
{
//1.委托的定义:声明委托类型(返回值和参数);定义委托对象;
//DelSayHi del = SayChinese;
//del("22");
//DelSayHi del = delegate(string name){Console.WriteLine("吃了么?" + name);};
//del("22");
//DelSayHi del = (name) => { Console.WriteLine("吃了么?" + name); };
//del("112233"); //
Test("", SayChinese);
//3 匿名函数
Test("", delegate(string name) { Console.WriteLine("吃了么?" + name); });
//4 lamda表达式
Test("", (name) => { Console.WriteLine("吃了么?" + name); }); Console.ReadKey();
} public static void Test(string name, DelSayHi del)
{
//调用
del(name);
}
public static void SayChinese(string name)
{
Console.WriteLine("吃了么?" + name);
}
public static void SayEnglish(string name)
{
Console.WriteLine("Nice to meet you" + name);
} }
}
2. 匿名函数 lamda表达式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace delegate2
{
public delegate string DelString(string name);
class Program
{
static void Main(string[] args)
{ string[] names = { "abCDefG", "HIJKlmnOP", "QRsTuW", "XyZ" }; //转大写 lamda
DealString(names, (name) => { return name.ToUpper(); });
//转大写 匿名函数
DealString(names, delegate(string name) { return name.ToUpper(); }); foreach (string item in names)
{
Console.WriteLine(item);
}
Console.ReadKey();
} static void DealString(string [] names ,DelString del2)
{
for (int i = ; i < names.Length; i++)
{
names[i] = del2(names[i]);
}
} }
}
3.求取任意数组的最大值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace delegate3
{
public delegate int DelCompare(object t1,object t2);
class Program
{
static void Main(string[] args)
{
object[] nums = { , , , , , , , , };
object[] strings = { "", "", "" };
object[] persons = { new person(,""),new person(,""),new person(,"")}; //int 数组
object i =GetMax(nums,delegate(object max,object num){
int IntMax =(int)max;
int IntNum=(int)num;
int result=IntMax-IntNum;
return result;
});
Console.WriteLine(i); //string 数组
object j = GetMax(strings, (max, num) =>
{
string s_max = (string)max;
string s_num = (string)num;
return s_max.Length - s_num.Length;
});
Console.WriteLine(j); //对象 数组
object oldPserson = GetMax(persons, (max, num) =>
{
person s_max = (person)max;
person s_num = (person)num;
return s_max.Age - s_num.Age;
});
Console.WriteLine(((person)oldPserson).Name);
Console.ReadKey();
} static object GetMax(object [] nums,DelCompare del)
{
object max = nums[];
for (int i = ; i < nums.Length; i++)
{
if (del(max,nums[i]) < )
max = nums[i];
}
return max;
}
} class person
{
public person(int _age, string _name)
{
Age = _age;
Name = _name;
}
public int Age { get; set; }
public string Name{get;set;}
}
}
4.泛型委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace delegate4
{
public delegate int DelCompare<T>(T t1, T t2);
class Program
{
static void Main(string[] args)
{
int[] nums = { , , , , , , , , }; int i = GetMax<int>(nums, (max, num) => {
return max - num;
}); Console.WriteLine(i);
Console.ReadKey();
} static T GetMax<T>(T[] nums, DelCompare<T> del)
{
T max = nums[];
for (int i = ; i < nums.Length; i++)
{
if (del(max, nums[i]) < )
max = nums[i];
}
return max;
}
}
}
5.窗体之间的传值


Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fm2 = new Form2();
fm2.showtt = ShowLab;
fm2.Show();
}
private void ShowLab(string tt)
{
this.label1.Text = tt;
}
}
}
Form2.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public delegate void ShowDele(string tt);
public partial class Form2 : Form
{
public ShowDele showtt;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string temp = this.textBox1.Text.Trim();
showtt(temp);
}
}
}
6.事件 (安全类型的委托!)
**事件只能在声明事件的那个类中被调用!类以外只能注册这个事件!
类中声明事件,调用事件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; namespace _06使用Winform应用程序模拟事件
{ public delegate void DelPlayOver();
class PlayMusic
{
public event DelPlayOver Del;//声明事件不需要写() //音乐播放的名字
public string Name { get; set; } public PlayMusic(string name)
{
this.Name = name;
} public void PlaySongs()
{
Console.WriteLine("正在播放" + this.Name);
//模拟播放了三秒钟
Thread.Sleep(); if (Del != null)
{
//当播放完成后 执行一个事件
Del();//直接调用“事件”
}
}
}
}
类的外面,(另一个类中注册事件):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace _06使用Winform应用程序模拟事件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
PlayMusic p = new PlayMusic("忐忑");//创建对象 开始播放音乐
p.Del += Test;//注册事件
p.PlaySongs();//开始播放音乐
} //事件要执行的函数
void Test()
{
//Console.WriteLine("播放完成了!!!!");
MessageBox.Show("播放完成了!!!");
}
}
}
7.反射
a.理解程序集:包含资源文件,类型元数据,exe,dll.
程序集可以看做是一堆相关类的打一个包,相当于java中的jar包。
b.反射:动态获取一个程序集中的元数据的功能!
c.AssemblyInfo.cs程序集相关信息
d.程序集的好处(扩展性)
e.如何添加程序集的引用
1.添加引用;2.添加命名空间;3.Public关键字
f.反射!!!
Type类,通过它可以获取类中的所有信息包括方法,属性;可以动态调用类的属性,方法;Type是对类的描述。
反射就是通过.dll来创建对象,调用成员。
g.步骤
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;//1.反射命名空间 namespace Reflection
{
class Program
{
static void Main(string[] args)
{
//2.加载程序集文件,绝对路径
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Common.dll");
Assembly ass = Assembly.LoadFile(path); //3.Assembly类 的方法GetExportedTypes,GetType,GetTypes
//Type[] types = ass.GetExportedTypes();
//foreach (Type item in types)
//{
// Console.WriteLine(item.FullName);
//}
//Type t = ass.GetType("Common.Person"); //4.动态创建对象
//调用了person类中默认无参数的构造函数!
/*
object o = ass.CreateInstance("Common.Person");
Console.WriteLine(o.GetType());
* */ //如果类中没有默认无参数的构造函数!
Type t = ass.GetType("Common.Person");
object o = Activator.CreateInstance(t, "张三", );
Console.WriteLine(o.GetType()); PropertyInfo[] pros = o.GetType().GetProperties();
foreach (PropertyInfo item in pros)
{
Console.WriteLine(item.Name);
} //调用Person类中的SayHello
MethodInfo mdi = o.GetType().GetMethod("SayHello");
mdi.Invoke(o, null); Console.ReadKey();
}
}
}
程序集中的相关类:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text; namespace Common
{
public class Person
{
public void Write()
{
File.WriteAllText("1.txt", "张三李四王五赵六天气");
}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
public int Age { get; set; }
public string Name { get; set; }
public void SayHello()
{
Console.WriteLine("我是Person类中的函数");
}
}
}
8.反射常用的函数
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection; namespace Reflection常用函数
{
class Program
{
static void Main(string[] args)
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Common.dll");
Assembly ass = Assembly.LoadFile(path); Type t_person = ass.GetType("Common.Person");
Type t_stu = ass.GetType("Common.Student");
Type t_tea = ass.GetType("Common.Teacher"); //Common.Person对象
object o_person = Activator.CreateInstance(t_person, "xx", );
PropertyInfo pro =o_person.GetType().GetProperty("Age");
//Console.WriteLine(pro.GetValue(o_person));//获取属性值 //bool t = t_person.GetType().IsAssignableFrom(t_stu.GetType());
//bool t = o_person.GetType().IsAssignableFrom(t_person.GetType());//里氏转换,判断是否父类子类 //bool t = t_tea.GetType().IsInstanceOfType(o_person); //判断指定的对象是否是当前类的实例 bool t = t_stu.GetType().IsSubclassOf(t_person.GetType());
//判断当前类是否是指定类的子类 Console.WriteLine(t);
Console.ReadKey(); }
}
}
C#面向对象22 委托事件反射的更多相关文章
- Asp.Net SignalR 使用记录 技术回炉重造-总纲 动态类型dynamic转换为特定类型T的方案 通过对象方法获取委托_C#反射获取委托_ .net core入门-跨域访问配置
Asp.Net SignalR 使用记录 工作上遇到一个推送消息的功能的实现.本着面向百度编程的思想.网上百度了一大堆.主要的实现方式是原生的WebSocket,和SignalR,再次写一个关于A ...
- [.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程
[.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程 本节导读:本节主要介绍什么是.NET反射特性,.NET反射能为我们做些什么,最后介绍几种常用的 ...
- 简学Python第七章__class面向对象高级用法与反射
Python第七章__class面向对象高级用法与反射 欢迎加入Linux_Python学习群 群号:478616847 目录: Python中关于oop的常用术语 类的特殊方法 元类 反射 一.P ...
- c#委托事件入门--第二讲:事件入门
上文 c#委托事件入门--第一讲:委托入门 中和大家介绍了委托,学习委托必不可少的就要说下事件.以下思明仍然从事件是什么.为什么用事件.怎么实现事件和总结介绍一下事件 1.事件是什么:. 1.1 NE ...
- C# 委托 事件
一:什么叫委托 通过反射发现,委托其实是一个类,继承自System.MulticastDelegate,但是System.MulticastDelegate这个类是特殊类,不能被继承 二:委托的声明 ...
- [.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦
[.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦 本节导读:上篇文章简单介绍了.NET面向对象中一个重要的技术反射的基本应用,它可以让我们动态的调 ...
- C# ~ 从 委托事件 到 观察者模式 - Observer
委托和事件的部分基础知识可参见 C#/.NET 基础学习 之 [委托-事件] 部分: 参考 [1]. 初识事件 到 自定义事件: [2]. 从类型不安全的委托 到 类型安全的事件: [3]. 函数指针 ...
- C#委托,事件理解入门 (译稿)
原文地址:http://www.codeproject.com/Articles/4773/Events-and-Delegates-Simplified 引用翻译地址:http://www.cnbl ...
- 关于ios使用jquery的on,委托事件失效
$('.parents').on("click",'.child',function(){}); 类似上面这种,在ios上点击"child"元素不会起作用,解决 ...
随机推荐
- 性能测试 | Web端性能测试
这篇文章想跟大家分享关于Web性能测试的一些知识点.在分享之前,我想先跟大家分享一组数据,关于为什么要做性能测试?具体如下: 71%用户希望在手机上打开网页能跟电脑一样快: 5秒钟被认为是用户能忍受的 ...
- 使用LuceneUtil工具类,完成CURD操作
package loaderman.curd; import java.util.ArrayList; import java.util.List; import loaderman.entity.A ...
- JavaScript中"Uncaught TypeError: Cannot set property 'innerHTML' of null"错误
写了一个函数,在调用时出错:"Uncaught TypeError: Cannot set property 'innerHTML' of null" 代码如下: <!DOC ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_5-5.HttpClient4.x工具获取使用
笔记 5.HttpClient4.x工具获取使用 简介:讲解httpClient4.x相关依赖,并封装基本方法. 1.加入依赖 <dependency> ...
- LVS系列一、LVS集群-NAT模式
一. 集群概述 1. 什么是集群? 一组各自相互独立且又相互依赖的,通过高速网络互联的计算机组成的一个计算机组, 以单一的系统模式加以管理, 为用户提供服务, 对用户来说, 用户只会认为对方是一个服务 ...
- 树莓派-Ubuntu Mate开启ssh服务
1. 运行 apt search openssh-server 查看是否安装ssh服务. 2. 如已安装,运行 sudo dpkg-reconfigure openssh-server 重新配置shh ...
- babylon 初试
出于对web端3D技术的对比,以及WebGL的发展现状和WebGPU的发展前景,我觉得有必要涉猎一下babylon.js了. 可以参考一下下列文章: 1⃣️下一代web端图形接口现状与前景:https ...
- unieap 导出文档错误
java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalCon ...
- Gitlab-Runner基础教程
一.Intro jenkins和runner,作为主流自动化运维工具来说,两者的大思路其实是一样的,就是将我们提交到代码仓库的代码拉到jenkins或者runner运行的机器里,然后执行一系列的命令( ...
- LeetCode.1160-找到可以由给定字符组成的字符串(Find Words That Can Be Formed by Characters)
这是小川的第411次更新,第443篇原创 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第262题(顺位题号是1160).你会得到一个字符串单词数组和一个字符串chars.如果字符串可 ...