将方法隐式转换为 Func<T, Tresult>

Implicit conversion of a method to Func<T, Tresult>

我有一个扩展 class 扩展 Func<T, TResult> 其签名如下所示:

public static ITryAndReturnValue<TResult> Try<T, TResult>(this Func<T, TResult> func, T arg, int retries)

我可以通过将方法转换为 Func<T, TResult> 来在方法上实现它...

Func<string, string> func  = request.DownloadString;
string response = func.Try(urlA, 3);

但我真正想做的是:

string response = request.DownloadString.Try(urlA, 3);

但是我得到这个编译时错误。

CS0119 'WebClient.DownloadString(string)' is a method, which is not valid in the given context

我可以做些什么来让我的扩展方法像我想要的那样工作吗?

Is there anything I can do to get my extension method to work like I want it to?

没有

扩展方法明确设计为在方法组上工作。

不,您不能在方法组或匿名函数上调用扩展方法。

C# 规范的第 7.6.5.2 节要求:

An implicit identity, reference or boxing conversion exists from expr to the type of the first parameter of Mj.

(其中 expr 是您尝试调用扩展方法的表达式,而 Mj 是扩展方法本身.)

一个方法组转换(允许你写Func<string, string> func = request.DownloadString;的转换)是不是一个身份、参考或拳击转换。这是一种单独的转换(规范的第 6.6 节)。