Rau*_*otz 7 lambda lazy-evaluation c#-3.0
lambda表达式的一个优点是,只有在需要结果时才需要计算函数.
在下面(简单)示例中,仅在编写器存在时才评估文本函数:
public static void PrintLine(Func<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text());
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这使得使用代码有点难看.你不能用常量或变量来调用它
PrintLine("Some text", Console.Out);
Run Code Online (Sandbox Code Playgroud)
并且必须这样称呼它:
PrintLine(() => "Some text", Console.Out);
Run Code Online (Sandbox Code Playgroud)
编译器无法从传递的常量"推断"无参数函数.有没有计划在未来的C#版本中改进这一点,还是我错过了什么?
更新:
我自己发现了一个肮脏的黑客:
public class F<T>
{
private readonly T value;
private readonly Func<T> func;
public F(T value) { this.value = value; }
public F(Func<T> func) {this.func = func; }
public static implicit operator F<T>(T value)
{
return new F<T>(value);
}
public static implicit operator F<T>(Func<T> func)
{
return new F<T>(func);
}
public T Eval()
{
return this.func != null ? this.func() : this.value;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我可以将函数定义为:
public static void PrintLine(F<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text.Eval());
}
}
Run Code Online (Sandbox Code Playgroud)
并用函数或值来调用它.
那么这两种说法是完全不同的。一种是定义函数,另一种是语句。混淆语法会更加棘手。
() => "SomeText" //this is a function
"SomeText" //this is a string
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6957 次 |
| 最近记录: |