C# new [delegate] not necessary?(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] 没必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# new [delegate] 没必要?
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
