温故而知新带有命名方法的委托和带有匿名方法的委托

委托可以与命名方法关联。使用命名方法对委托进行实例化时,该方法将做为参数传递。例如:

delegate void Del(int x);

void Do(int k){/*...*/}

Del d=obj.Do();

这种称为使用命名的方法。使用命名方法构造的委托可以封装静态方法或实例方法。

以前,命名方法是对委托进行实例化的唯一方式。现在,不希望付出创建新方法的系统开销。C#可以对委托进行实例化,并立即指定委托在被调用时将处理的代码块。代码块可以包含Lamb大、表达式或匿名方法。

注:

作为委托参数传递的方法必须与委托声明具有相同的签名。

委托实例可以封装静态或实例方法。

委托可以使用out参数,但建议不要在多路广播事件委托中使用,因为无法知道哪个委托将被调用。

下面是一个声明使用委托的简单例子。注意Del委托和关联的方法具有相同的签名。

delegate void Del(int i,double j);
    class MathClass
    {
        static void Main(string[] args)
        {
            MathClass m = new MathClass();
            Del d = m.MultiplyNumbers;
            for (int i = 1; i < 5; i++)
            {
                d(i, 3);
            }
            Console.ReadKey();
        }
        void MultiplyNumbers(int m, double n)
        {
            Console.Write(m * n + "  ");
        }
    }

下面是一个委托被同事映射到静态方法和实例方法,并分别返回特定的信息。

 1 delegate void Del();
 2     class MathClass
 3     {
 4         static void Main(string[] args)
 5         {
 6             MathClass m = new MathClass();
 7             Del d = m.InstanceMethod;
 8             d();
 9             d = MathClass.StaticMethod;
10             d();
11             Console.ReadKey();
12         }
13         public void InstanceMethod()
14         {
15             Console.WriteLine("instance method");
16         }
17         static public void StaticMethod()
18         {
19             Console.WriteLine("static method");
20         }
21     }

原文地址:https://www.cnblogs.com/zhangxiaohui/p/2553424.html