委托 vs 动作,C# 中的 Func
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17888480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delegates vs Action, Func in C#
提问by anfri
This might seem a silly question, but it's just for curiosity's sake.
这似乎是一个愚蠢的问题,但这只是为了好奇。
We have two particular already-defined delegates in C#:
我们在 C# 中有两个特定的已定义委托:
Action encapsulates any"void" method that takes 0 or more parameters.
Func encapsulates anymethod that returns a specific value type and takes 0 or more parameters.
Action 封装了任何带有 0 个或多个参数的“void”方法。
Func 封装了任何返回特定值类型并带有 0 个或多个参数的方法。
My question is: in which cases it is recommended to define a custom delegate?
Why would you need to do that?
Thanks in advance
我的问题是:在哪些情况下建议定义自定义委托?
为什么你需要这样做?
提前致谢
采纳答案by Lee
None of the Func
or Action
types allow out
or ref
parameters, so you'll have to define your own delegates if you need to use those e.g.:
的无Func
或Action
类型允许out
或ref
参数,所以你必须定义自己的代表,如果你需要使用那些例如:
public delegate bool TryParse<T>(string s, out T value);
回答by Arghya C
In thousand cases you'll need to refer/point to a function (hence a delegate, if actual implementation of the function will vary at run time, except the signature) that doesn't match either of the given delegates. Say
在数千种情况下,您需要引用/指向与给定委托中的任何一个都不匹配的函数(因此是委托,如果函数的实际实现在运行时会有所不同,签名除外)。说
Public delegate T MyDel(T t, U u, V v);
公共代表 T MyDel(T t, U u, V v);