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

喜你入骨 提交于 2019-11-27 13:23:53

问题


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 ?

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.


回答1:


There's no difference at all. The second is just a shorthand for Invoke, provided by the compiler. They compile to the same IL.




回答2:


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;


来源:https://stackoverflow.com/questions/16309286/funct-vs-funct-invoke

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!