委托(轉)
来源:互联网 发布:js input disabled 编辑:程序博客网 时间:2024/06/06 15:02
1.什么是委托?
委托是一种定义方法签名的类型,可以与具有兼容签名的任何方法关联。
2.委托有什么特点?
- 委托类似于 C++ 函数指针,但它们是类型安全的。
- 委托允许将方法作为参数进行传递。
- 委托可用于定义回调方法。
- 委托可以链接在一起;例如,可以对一个事件调用多个方法。
- 方法不必与委托签名完全匹配。
- C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。
- C# 3.0 引入了 Lambda 表达式,利用它们可以更简练地编写内联代码块。匿名方法和 Lambda 表达式(在某些上下文中)都可编译为委托类型。这些功能统称为匿名函数。
3.如何使用委托?
Demo:
using System;namespace ConsoleApplication28{ class Program { public static void FunctionA(string strMessage) { Console.WriteLine(strMessage); } public delegate void DelegateMethod(string strMessage); static void Main(string[] args) { DelegateMethod handler = FunctionA; handler("Hello Kevin"); } }}
4.匿名方法
在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,通过使用匿名方法,由于您不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。以下是两个使用匿名方法的示例:
Demo1:
using System;using System.Windows.Forms;namespace WindowsFormsApplication10{ public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += delegate(object sender, EventArgs e) { MessageBox.Show("The box is click"); }; } private void Form1_Load(object sender, EventArgs e) { } }}
Demo2:
void StartThread() { Thread t1 = new Thread (delegate() { MessageBox.Show("Hello,"); MessageBox.Show("Kevin"); }); t1.Start(); }
5.合并委托(多路广播委托)
Demo:
using System;namespace ConsoleApplication29{ delegate void DelegageMethod(); class Program { static void A() { Console.WriteLine("A"); } static void B() { Console.WriteLine("B"); } static void Main(string[] args) { DelegageMethod a, b, c, d; a = A; b = B; c = a + b; d = c - a; Console.WriteLine("Invoking delegate a:"); a(); Console.WriteLine("Invoking delegate b:"); b(); Console.WriteLine("Invoking delegate c:"); c(); Console.WriteLine("Invoking delegate d:"); d(); } }}
- 委托(轉)
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- 委托
- WPE详细教程四 滤镜制作(4)
- WPE详细教程四 独立外挂制作(1)
- 关于this和super的区别
- WPE详细教程四 独立外挂制作(2)
- 惠普大中华区总裁孙振耀退休感言
- 委托(轉)
- struts应用中JSP页面链接CSS样式表的路径问题
- 传智播客Hibernate视频教程学习笔记47
- 网络游戏外挂编写基础一
- c sdk 建立窗口的步骤
- 网络游戏外挂编写基础二
- 饱受好评的免费屏幕录像软件:Wink
- pku 3349 Snowflake Snow Snowflakes(hash,最小表示法)
- WPE实际经验和实例