委托(轉)

来源:互联网 发布: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();        }    }}
原创粉丝点击