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"元素不会起作用,解决 ...
随机推荐
- javascript实现集合Set、字典Dictionary、HashTable
集合是由一组无序且唯一(即不能重复)的项组成的.这个数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中. function Set() { this.items = {}; } S ...
- python编码,三个编码实例
1.字符串编码设置 data = u'你好' utf8 = data.encode('utf-8') 2.管道编码设置 import locale import sys ###设置输出管道编码### ...
- 码支付(php版本)应用
1.下载软件 2.安装php 版本 2.打开软件,登陆支付宝 3.codepay_config.php 中填写逻辑代码 4.充值路径: 说明:$username = trim($_GET['user ...
- Jmeter接口上传文件
一.使用抓包软件抓取该接口,查看参数(图例使用的是charles) 可以看到上传文件的参数名是file1 二.把抓取到的普通参数都放在参数这一栏里,如图所示,不要在意马赛克 三.参数名称写在如图所示的 ...
- tensorflow安装过程-(windows环境下)---详解
一, 前言:本次安装tensorflow是基于Python的,安装Python的过程不做说明(既然决定按,Python肯定要先了解啊):本次教程是windows下Anaconda安装Tensorflo ...
- JAVA中注解的实现原理
注解的本质 「java.lang.annotation.Annotation」接口中有这么一句话,用来描述『注解』. The common interface extended by all anno ...
- redis开启持久化、redis 数据备份与恢复
redis持久化介绍 https://segmentfault.com/a/1190000015897415 1. 开启aof持久化.以守护进程启动.远程访问先把配置文件拷贝一份到/etc/redi ...
- 【HTML】常用的标签学习
HTML(HyperText Markup Language )又称超文本标记语言,与一般文本文件不同的是它是由各种标签或标记组成 <标签名></标签名> .所以html的学习 ...
- 【Abode Air程序开发】在设备上进行安装
在设备上进行安装 在 Google Android 设备上安装应用程序 在 Apple iOS 设备上安装应用程序 在 Google Android 设备上安装应用程序 在项目的开发.测试和部署阶段, ...
- 调用存储在session属性里的东西
将对象放在session里面 request.getSession().setAttribute("username", username); //放到会话里 永EL表达式调用 $ ...