1.在 C# 1.0 及更高版本中,可以按以下示例所示声明委托。
// Declare a delegate. delegate void Del(string str); // Declare a method with the same signature as the delegate. static void Notify(string name) { Console.WriteLine("Notification received for: {0}", name); } // Create an instance of the delegate. Del del1 = new Del(Notify);
// 调用委托:del1("参数");
2.C# 2.0 提供了更简单的方法来编写上面的声明,如以下示例所示。
// Instantiate Del by using an anonymous method. Del del3 = delegate(string name) { Console.WriteLine("Notification received for: {0}", name); }; //调用委托:del3("参数");
3.在 C# 3.0 及更高版本中,还可以使用 Lambda 表达式来声明和实例化委托,如以下示例所示。
// Instantiate Del by using a lambda expression. Del del4 = name => { Console.WriteLine("Notification received for: {0}", name); };//调用委托:del4("参数");
时间: 2024-10-13 16:09:54