本文介绍了手动创建代表VS使用Action / FUNC代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我在想声明这个:

Today I was thinking about declaring this:

private delegate double ChangeListAction(string param1, int number);

但为什么不利用这样的:

but why not use this:

private Func<string, int, double> ChangeListAction;

ChangeListAction 将没有返回值,我可以使用:

or if ChangeListAction would have no return value I could use:

private Action<string,int> ChangeListAction;

这样的优势到底在哪里在宣布与委托的委托关键字?

是不是因为.NET 1.1,和.NET 2.0来了动作&LT; T&GT; ,并在.NET 3.5来了 Func键&LT; T&GT;

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.

这也将帮助你,当你正在写的code。这样的错误:

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>

比其中一个说没有多大帮助:

is less helpful than one which says:

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.

这篇关于手动创建代表VS使用Action / FUNC代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:48
查看更多