zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    设计模式-状态模式
    设计模式-策略模式
    Spring MVC 梳理
    Spring MVC 梳理
    设计模式-总结
    Spring boot 梳理
    Spring boot 梳理
    [DP题]最长上升子序列
    NOIP2013 Day1
    20171025日程
  • 原文地址:https://www.cnblogs.com/netfork/p/3835.html
Copyright © 2011-2022 走看看