lambda表达式的一个优点是只有在需要结果时才需要计算函数。C#lambda表达式和懒惰评估
在下面的(简单)例如,文本功能仅被评估时,作者是本:
public static void PrintLine(Func<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text());
}
}
不幸的是,这使得使用代码有点难看。你不能用一个固定或可变称呼它
PrintLine("Some text", Console.Out);
,并有打电话这样说:
PrintLine(() => "Some text", Console.Out);
编译器是无法从通过不断“推断”无参数的函数。有没有计划在未来版本的C#中改进这一点,或者我错过了什么?
UPDATE:
我只是找到了一个肮脏的黑客自己:
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;
}
}
现在就可以定义功能:
public static void PrintLine(F<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text.Eval());
}
}
与函数或调用它都值。
我同意。在添加过载的情况下,不可能区分[如果支持这种快捷方式]。 – Krisc 2010-04-27 18:22:33