c# - 获得一个无参数的方法来像 Func<Return>

标签 c# lambda extension-methods fluent-interface

我正在努力使我的部分代码更加流畅。

我有一个字符串扩展,可以从字符串中发出 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/

相关文章:

c# - 如何将具有动态值的 javascript 对象发布到 mvc6 Controller 操作

c# - 参数 : (required, optional) vs (required, required, optional)

c++ - 如何返回一个 lambda 函数?

java - 通过排序规则合并两个流

c# - 使用动态类型调用泛型扩展方法

c# - 为什么我们在 LINQ 中需要 Single()?

c# - 如何统计我的列的总数?

c# - MessageBox.Show ("First Name,{0}", textBox1.Text);

lambda - Java 8 - 在 List 中存储 lambdas

c# - 列表扩展方法的 Microsoft.Maintainability 错误