Func < T >() vs Func < T > . Invoke()

我很好奇直接调用 Func<T>与使用 Invoke()之间的区别。有区别吗?第一个语法 Sugar 和调用 Invoke()是在下面吗?

public T DoWork<T>(Func<T> method)
{
return (T)method.Invoke();
}

对。

public T DoWork<T>(Func<T> method)
{
return (T)method();
}

还是我完全走错路了?

32069 次浏览

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 works well with new C# 6 null propagation operator, now you can do

T result = method?.Invoke();

instead of

T result = method != null ? method() : null;