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"元素不会起作用,解决 ...
随机推荐
- JS基础_数组的方法
常用的方法 1.push:向数组的末尾添加一个或更多元素,并返回新的长度. 将要添加的元素作为方法的参数传递,这些元素将会自动添加到数组的末尾 var a=[1,2,3]; var r = a.pus ...
- shapefile 输出的地理处理注意事项
多年来,ESRI 为存储地理信息开发了三种主要数据格式 - coverage 格式.shapefile 格式及地理数据库格式.其中,所开发的 Shapefile 为存储地理及属性信息提供了一种简单的非 ...
- 影响mysql性能的因素
一.服务器硬件. CPU不够快,内存不够多,磁盘IO太慢. 对于计算密集型的应用,CPU越可能去影响系统的性能,此时,CPU和内存将越成为系统的瓶颈. 当热数据大小远远超过系统可用内存大小时,IO资源 ...
- HTTP请求协议中请求报文(Request Headers)跟响应报文(Response Headers)的简单理解
背景 今儿个一新来的应届生问我,开发模式中所看到的web请求的请求头里的属性怎么理解,我便根据自己的经验随便拉开一个请求跟他聊了起来,顺便自己记录下文字版,以后再有交流直接发地址给他就好了,嘻嘻,机智 ...
- 14 statefulset (sts)控制器
statefulset (sts)控制器 可以用于部署有状态的服务,比如说redis,mysql ,zk等等... 1. 稳定且唯一的网络标志符:2. 稳定且持久的存储3. 有序,平滑地部署和扩展:4 ...
- Rancher-k8s加速安装文档
Kubernetes是一个强大的容器编排工具,帮助用户在可伸缩性系统上可靠部署和运行容器化应用.Rancher容器管理平台原生支持K8s,使用户可以简单轻松地部署K8s集群. 很多同学正常部署k8s环 ...
- Ubuntu 安装 docker,并上传到dockerhub
一.安装Docker apt-get -y install docker.io 链接: ln -sf /usr/bin/docker.io /usr/local/bin/docker 检查docker ...
- WebServer_简单例子
#-*-coding:utf-8-*- importwebimportjson urls=("/.*","index")app=web.application( ...
- JAVA 基础编程练习题12 【程序 12 计算奖金】
12 [程序 12 计算奖金] 题目:企业发放的奖金根据利润提成.利润(I)低于或等于 10 万元时,奖金可提 10%:利润高于 10 万元, 低于 20 万元时,低于 10 万元的部分按 10%提成 ...
- vue是一个渐进式的框架,我是这么理解的
vue是一个渐进式的框架,我是这么理解的 原文地址 时间:2017-10-26 10:37来源:未知 作者:admin 每个框架都不可避免会有自己的一些特点,从而会对使用者有一定的要求,这些要求就是主 ...