gpt4 book ai didi

c# - 将方法隐式转换为 Func

转载 作者:行者123 更新时间:2023-11-30 21:47:14 26 4
gpt4 key购买 nike

我有一个扩展类扩展 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

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

最佳答案

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

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 节)。

关于c# - 将方法隐式转换为 Func<T, Tresult>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com