本文介绍了C# new [delegate] 没必要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been playing with HttpWebRequests lately, and in the tutorials they always do:

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

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

But new AsyncCallback doesn't seem to be necesary. If UpdateItem has the right signature, then there doesn't seem to be a problem. So why do people include it? Does it do anything at all?

推荐答案

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

It's the same thing, mostly (there are a few overload rules to think about, although not in this simple example). But in previous versions of C#, there wasn't any delegate type inference. So the tutorial was either (a) written before delegate type inference was available, or (b) they wanted to be verbose for explanation purposes.

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

Here's a summary of a few of the different ways you can take advantage of delegate type inferencing:

// 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(); });

这篇关于C# new [delegate] 没必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:13