为什么Action <T>和Predicate <T>被使用或定义为委托?

Won*_*ing 4 c# delegates

有人可以解释在C#中使用Action<T>Predicate<T>作为代理的原因是什么

Jim*_*hel 11

你问他们为什么存在,或者为什么他们被定义为代表?

至于它们为什么存在,也许最好的理由是方便.如果你想要一个不返回值的委托并且只接受某种类型的单个参数,你可以自己定义它:

public delegate void MyDelegate(int size);
Run Code Online (Sandbox Code Playgroud)

然后再创建一个:

MyDelegate proc = new MyDelegate((s) => { // do stuff here });
Run Code Online (Sandbox Code Playgroud)

当然,你必须为你想拥有这种方法的每种不同类型做到这一点.

或者,你可以使用Action<T>:

Action<int> proc = new Action<int>((s) => { /* do stuff here */ });
Run Code Online (Sandbox Code Playgroud)

当然,你可以缩短到:

Action<int> proc = (s) => { /* do stuff here */ });
Run Code Online (Sandbox Code Playgroud)

至于"他们为什么代表?" 因为这是在.NET中操作函数引用的方式:我们使用委托.请注意上面示例中的相似之处.也就是说,MyDelegate概念上与a是一样的Action<int>.它们不是完全相同的,因为它们有不同的类型,但你可以轻松地用MyDelegate程序替换它中的每个实例Action<int>,并且程序可以工作.