委托的几种写法

参考自Jeffrey Zhao的文章(http://www.cnblogs.com/jeffreyzhao/archive/2009/08/07/from-delegate-to-others-2.html

.NET1.X

public delegate void MyDel3(string message);

public class Methods
{
public static void TestMethod(string msg)
{
Console.WriteLine(msg);
}

public void TestMethod2(string msg)
{
Console.WriteLine(msg);
}
}

public class DelTest
{
public void Execute()
{
MyDel3 del3 = new MyDel3(Methods.TestMethod);
Methods methods = new Methods();
del3 += new MyDel3(methods.TestMethod2);
}
}

需要使用new DelegateType(**)来创建

 

.NET2.0

    public static void Execute(string message)
{
Test2(delegate(int a, string b) { Console.WriteLine(message); }, "");
}


private static void Test2(Action<int, string> action, string msg)
{
action(100, msg);
}
  1. 可以直接进行赋值,而不需要使用new DelegateType()
  2. 最重要的是可以使用匿名方法,如上,好处在于可以直接使用方法内的参数(message),而不需要另外封装、传递

.NET3.5

可以使用Lambda表达式,代码更加简洁。

posted @ 2012-01-10 17:38  Müller  阅读(647)  评论(0编辑  收藏  举报