C# new [delegate] 没必要?

C# new [delegate] not necessary?(C# new [delegate] 没必要?)
本文介绍了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] 没必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)