我正在努力使我的部分代码更加流畅。
我有一个字符串扩展,可以从字符串中发出 HTTP 请求并以字符串形式返回响应。所以我可以做类似...
string _html = "http://www.stackoverflow.com".Request();
我正在尝试编写一个扩展程序,它将不断尝试请求直到成功。我的签名看起来像...
public static T KeepTrying<T>(this Func<T> KeepTryingThis) {
// Code to ignore exceptions and keep trying goes here
// Returns the result of KeepTryingThis if it succeeds
}
我打算称它为...
string _html = "http://www.stackoverflow.com".Request.KeepTrying();
唉,这似乎行不通 =)。我尝试先将它变成 lambda,但这似乎也不起作用。
string _html = (() => "http://www.stackoverflow.com".Request()).KeepTrying();
有没有办法在保持语法相当流畅的同时完成我想做的事情? 非常感谢您的建议。
谢谢。
最佳答案
您不能将方法组用于扩展方法或 lambda 表达式。我 blogged about this a while ago .
我怀疑你可以转换为 Func<string>
:
string _html = ((Func<string>)"http://www.stackoverflow.com".Request)
.KeepTrying();
但这很讨厌。
一种替代方法是更改 Request()
返回一个Func,并使用:
string _html = "http://www.stackoverflow.com".Request().KeepTrying();
或者如果你想保留 Request
方法本身很简单,就是加一个RequestFunc
方法:
public static Func<string> RequestFunc(this string url)
{
return () => url.Request();
}
然后调用:
string _html = "http://www.stackoverflow.com".RequestFunc().KeepTrying();
关于c# - 获得一个无参数的方法来像 Func<Return>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/801060/