C# Func<T>() 与 Func<T>.Invoke()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16309286/
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
Func<T>() vs Func<T>.Invoke()
提问by tris
I'm curious about the differences between calling a Func directly vs using Invoke() on it. Is there a difference ? Is the first, syntactical sugar, and calls Invoke() underneath anyway ?
我很好奇直接调用 Func 与在其上使用 Invoke() 之间的区别。有区别吗?是第一个语法糖,还是在下面调用 Invoke() 吗?
public T DoWork<T>(Func<T> method)
{
return (T)method.Invoke();
}
vs
对比
public T DoWork<T>(Func<T> method)
{
return (T)method();
}
Or am I on the wrong track entirely :) Thanks.
还是我完全走错了路 :) 谢谢。
采纳答案by Jon Skeet
There's no difference at all. The second is just a shorthand for Invoke, provided by the compiler. They compile to the same IL.
根本没有区别。第二个只是 的简写Invoke,由编译器提供。它们编译为相同的 IL。
回答by sanjuro
Invoke works well with new C# 6 null propagation operator, now you can do
Invoke 适用于新的 C# 6 空传播运算符,现在您可以这样做
T result = method?.Invoke();
instead of
代替
T result = method != null ? method() : null;

