【问题标题】:C# new [delegate] not necessary?C# new [delegate] 没必要?
【发布时间】:2009-12-27 07:29:44
【问题描述】:

我最近一直在玩HttpWebRequests,在教程中他们总是这样做:

IAsyncResult result = request.BeginGetResponse(
  new AsyncCallback(UpdateItem),state);

但是new AsyncCallback 似乎没有必要。如果UpdateItem 有正确的签名,那么似乎没有问题。那么人们为什么要包括它呢?它有什么作用吗?

【问题讨论】:

标签: c# delegates


【解决方案1】:

大部分情况下都是一样的(有一些重载规则需要考虑,虽然不是在这个简单的例子中)。但是在以前的 C# 版本中,没有任何委托类型推断。因此,本教程要么 (a) 在委托类型推断可用之前编写,要么 (b) 为了解释的目的,他们想要冗长。

以下是您可以利用委托类型推断的几种不同方式的摘要:

// Old-school style.
Chef(new CookingInstructions(MakeThreeCourseMeal));

// Explicitly make an anonymous delegate.
Chef(delegate { MakeThreeCourseMeal });

// Implicitly make an anonymous delegate.
Chef(MakeThreeCourseMeal);

// Lambda.
Chef(() => MakeThreeCourseMeal());

// Lambda with explicit block.
Chef(() => { AssembleIngredients(); MakeThreeCourseMeal(); AnnounceDinnerServed(); });

【讨论】:

    【解决方案2】:

    AsyncCallback 在 C# 中只是一个委托,它被声明为

    public delegate void AsyncCallback(IAsyncResult ar);
    

    当您传递方法名称本身时,只要签名匹配,编译器通常会为您替换代码,它只是快捷方式。

    您可以简单地使用Reflector 进行检查。例如,如果你有这个。

    request.BeginGetResponse(TestMethod, null);
    
     static void (IAsyncResult r)
            {
               //do something
            }
    

    编译后的代码实际上是这样的。

       request.BeginGetResponse(new AsyncCallback(Test), null);
    

    【讨论】:

      【解决方案3】:

      为了完整起见,这在 C# 1.2(带有 .NET 1.1)和 C# 2.0(带有 .NET 2.0)之间有所不同。因此,从 2.0 开始,您确实可以在大多数情况下省略 new SomeDelegateType(...)。奇怪的是,工具并没有改变,所以在 IDE 中,如果您键入 someObj.SomeEvent +=,IDE 将建议(通过 tab tab)完整版本,包括委托类型。

      【讨论】:

        猜你喜欢
        • 2011-12-05
        • 1970-01-01
        • 2016-03-31
        • 2010-10-05
        • 1970-01-01
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多