C# 委托语法
public delegate-typeof-delegate Delegate ();
委托基本上与指向函数的指针相关。
它保存方法的引用。委托是引用类型变量。
委托降低了代码复杂度,因为我们可以通过信号委托调用一系列方法。
如果我们想在需要委托时将方法作为参数传递,我们就必须操纵事件并回调方法。
C# 委托示例
using System;
namespace Onitroad
{
delegate void MyDelegate(string s);
class MyClass
{
public static void Hello(string s)
{
Console.WriteLine(" Hello, {0}!", s);
}
public static void Goodbye(string s)
{
Console.WriteLine(" Goodbye, {0}!", s);
}
public static void Main()
{
MyDelegate a, b, c, d;
a = new MyDelegate(Hello);
b = new MyDelegate(Goodbye);
c = a + b;
d = c - a;
Console.WriteLine("Invoking delegate a:");
a("A");
Console.WriteLine("Invoking delegate b:");
b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
Console.WriteLine("Invoking delegate d:");
d("D");
Console.ReadLine();
}
}
}
日期:2020-04-11 23:03:56 来源:oir作者:oir
