三种实例化委托的方式(C# 编程指南)

时间:2023-03-09 03:14:24
三种实例化委托的方式(C# 编程指南)

1.定义的委托和方法

    delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}

2.常规委托:

// Original delegate syntax required
// initialization with a named method.
TestDelegate testdelA = new TestDelegate(M);

3.匿名方法

 // C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

4.Lambda 表达式

 // C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };

相关文章