手动创建委托与使用 Action/Func 委托

Creating delegates manually vs using Action/Func delegates(手动创建委托与使用 Action/Func 委托)

本文介绍了手动创建委托与使用 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 委托

基础教程推荐