【问题标题】:What it means to have body in delegates declaration?在代表声明中有正文是什么意思?
【发布时间】:2012-08-17 14:01:51
【问题描述】:

我刚刚看到以下代码:

class X
{
  static Action Ac()
  {
     return ..some other code
  }
}

这是什么意思?我从未见过声明其主体的委托。

【问题讨论】:

    标签: c# delegates anonymous-methods


    【解决方案1】:

    这不是声明其主体的Action 委托。这是X 类的静态方法,名为Ac(),返回类型为Action;也就是说,它是一个返回Action 委托的类方法。主体可能会创建一个 Action 对象以从该方法返回。

    换句话说:它是一个常规的静态方法,它恰好返回Action,而不是stringint

    【讨论】:

    • :) 谢谢,没想到这么简单
    【解决方案2】:

    引用匿名方法的委托对象被声明为(使用旧语法并省略 lambda 表示法):

    Action<int> action = delegate (int x) { 
                            //this is a body of anonymous method
                            //which is referenced by a delegate object action of type Action<int>
                            Console.WriteLine (x);
                            };
    

    比这样称呼:

     action(5);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多