C#委托的学习了解

C#的委托(Delegate)类似于CC++的函数指针。委托是存有对某一个方法引用的一种引用变量类型,引用可在运行时被改变。

委托特别用于实现事件和回调方法。所有的委托都派生自System.Delegate类。

委托的声明

委托声明决定了可由该委托引用的方法,委托可指向一个与其有相同标签的方法。

以下是一个委托的声明

public delegate string newDelegate(string str);

该声明表示此委托可以引用任何一个单字符参数的方法并且返回值为bool类型。

声明语法

delegate <return type> <delegatename> (<paramter list>)

委托实例化

 委托实例化和实例化类一样,使用new关键字

newDelegate newDelegate = new newDelegate(function);

其中function为被引用的方法名,同一类作用域内只能引用静态的方法

委托的应用

定义一个委托,以及两个方法

    public delegate void delegateDemo();
    public class FunStudy
    {
        public void stepOne() 
        {
            Console.WriteLine("步骤一:打开冰箱门");
        }

        public void stepTwo() 
        {
            Console.WriteLine("步骤二:大象装冰箱里");
        } 
    }
        static void Main(string[] args)
        {
            FunStudy funStudy = new FunStudy();

            delegateDemo demo = funStudy.stepOne;
            demo += funStudy.stepTwo;
            demo();
        }

执行效果

原文地址:https://www.cnblogs.com/bzpfly/p/14278715.html