相当于C语言的指针,但不同的是委托是类型安全的。
声明格式如下:
属性集 修饰符 delegate 函数返回类型 定义的代表标识符(函数形参列表);
修饰符和上文接口一样。
delegate int MyDelegate();
public class MyClass{
public int InstanceMethod(){
Console.WriteLine("调用了非静态的方法");
return 0;
}
static public int StaticMethod(){
Console.WriteLine("调用了静态的方法");
return 0;
}
}
public class Test{
static void Main(string[] args)
{
MyClass p=new MyClass();
//用new建立MyDelegate代表类对象,d中存储非静态方法InstanceMethod的地址
MyDelegate d=new MyDelegate(p.InstanceMethod);
d();//调用非静态方法
//用new建立MyDelegate代表类对象,d中存储静态方法StaticMethod的地址
d=new MyDelegate(MyClass.StaticMethod);
d();//调用静态方法
}
}