1 委托是安全封装方法的类型,类似于 C 和 C++ 中的函数指针。 与 C 函数指针不同的是,委托是面向对象的、类型安全的和可靠的。 委托的类型由委托的
名称确定。Delegate 类,委托是一种数据结构,它引用静态方法或引用类实例及该类的实例方法,有属性和方法。
分为带有命名方法的委托与带有匿名方法的委托(C# 编程指南)
// 可以放在任何一个空文件中作全局MessengerCallback类型
public delegate void MessengerCallback();
public delegate void MessengerCallback<T>(T arg1);
public delegate void MessengerCallback<T,U>(T arg1, U arg2);
public delegate void MessengerCallback<T,U,V>(T arg1, U arg2, V arg3);
static void Main(string[] args)
{
// Original delegate syntax required
// initialization with a named method.
TestDelegate testDelA = new TestDelegate(M);
// 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); };
// 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); };
// Invoke the delegates.
testDelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}