C#的代表(delegate)

C#语言中取消了指针这个概念。当然,也可以在C#中使用C#,但必须声明这段程序是“非安全(unsafe)”。
在C#中,使用代表(delegate)来相当于C#中函数指针原型。代表在C#中是安全的。
在声明代表时,只需要指定代表指向的原型的类型。

public class MyClass
{
    public int InstanceMethod()
    {
        Console.WriteLine("Call the instance method.");
        return 0;
    }
   
    static public int StaticMethod()
    {
        Console.WriteLine("Call the method.");
        return 0;
    }
}
public class Test
{
    static public void Main()
    {
        MyClass p = new MyClass();
        // 将代表指向非静态的方法InstanceMethod
        MyDelegate d = new MyDelegate(p.InstanceMethod);
        // 调用非静态方法
        d();
        // 将代表指向静态的方法StaticMethod
        d = new MyDelegate(MyClass.StaticMethod);
        // 调用静态方法
        d();
    }
}
posted @ 2004-03-22 02:34  修多  阅读(646)  评论(1编辑  收藏  举报