Creating delegates manually vs using Action/Func delegates(手动创建委托与使用 Action/Func 委托)
问题描述
今天我正在考虑宣布这一点:
Today I was thinking about declaring this:
private delegate double ChangeListAction(string param1, int number);
但为什么不使用这个:
private Func<string, int, double> ChangeListAction;
或者如果 ChangeListAction 没有我可以使用的返回值:
or if ChangeListAction would have no return value I could use:
private Action<string,int> ChangeListAction;
那么使用 delegate 关键字声明委托的优势在哪里?
so where is the advantage in declaring a delegate with the delegate keyword?
是因为 .NET 1.1,而 .NET 2.0 出现了 Action<T>,而 .NET 3.5 出现了 Func<T>?
Is it because of .NET 1.1, and with .NET 2.0 came Action<T> and with .NET 3.5 came Func<T>?
推荐答案
优点是清晰.通过为类型指定一个明确的名称,读者可以更清楚地了解它的作用.
The advantage is clarity. By giving the type an explicit name it is more clear to the reader what it does.
它还会在您编写代码时为您提供帮助.像这样的错误:
It will also help you when you are writing the code. An error like this:
cannot convert from Func<string, int, double> to Func<string, int, int, double>
没有那么有用:
cannot convert from CreateListAction to UpdateListAction
这也意味着,如果你有两个不同的委托,它们都采用相同类型的参数,但在概念上做了两件完全不同的事情,编译器可以确保你不会意外地使用你想要的另一个.
It also means that if you have two different delegates, both of which take the same types of parameters but conceptually do two entirely different things, the compiler can ensure that you can't accidentally use one where you meant the other.
这篇关于手动创建委托与使用 Action/Func 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:手动创建委托与使用 Action/Func 委托
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
