C# new [delegate] not necessary?(C# new [delegate] 没必要?)
问题描述
我最近一直在玩 HttpWebRequest
,在教程中他们总是这样做:
I've been playing with HttpWebRequest
s 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] 没必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# new [delegate] 没必要?
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01