【发布时间】:2014-10-28 10:10:31
【问题描述】:
关于匿名方法,给定一个第一个参数为 Func 的方法“WriteConditional”,有没有办法甚至消除额外的“() =>”语法?
看起来你应该能够做到,因为它是明确的,只要没有额外的重载可以接受字符串,对吧?
void Program()
{
IDictionary<string,string> strings = new Dictionary<string,string>() { {"test","1"},{"test2","2"}};
//seems like this 'should' work, because WriteConditional has no other overload
//that could potentially make this ambiguous
WriteConditional(strings["test"],"<h3>{0}</h3>");
//since WriteConditional_2 has two overloads, one that has Func<string> and another with string,
//the call could be ambiguous, so IMO you'd definitely have to "declare anonymous" here:
WriteConditional_2(()=>strings["test"],"<h3>{0}</h3>");
}
void WriteConditional(Func<string> retriever, string format)
{
string value = retriever.Invoke();
if(string.IsNullOrEmpty(value)==false)
Console.WriteLine(string.Format(format,value));
}
void WriteConditional_2(Func<string> retriever, string format)
{
string value = retriever.Invoke();
if(string.IsNullOrEmpty(value)==false)
Console.WriteLine(string.Format(format,value));
}
void WriteConditional_2(string value, string format)
{
if(string.IsNullOrEmpty(value)==false)
Console.WriteLine(string.Format(format,value));
}
【问题讨论】:
-
is there a way to even eliminate the extra "() => " syntax?为什么(如果我没看错你的问题)?该语法专门表示匿名方法。读过的人,都懂。消除它意味着我不知道我会调用哪个方法签名,或者它试图做什么。 -
嗯,这个语法特指“lambda 表达式”。
delegate { return strings["test"]; }将是一个匿名方法。 -
您能否评论一下“......像这样'应该'如何工作,” - 将
string转换为函数的预期行为是什么? -
当然,任何带有任何参数的 lambda 显然都不会在这里考虑,因为您没有参数名称可以使用它。这消除了 lambda 的绝大多数实际用途。
-
这将要求编译器在知道它正在解析的内容之前进行大量的预测。这也意味着您无法仅通过语法来判断
foo(a)是立即评估还是延迟评估。
标签: c# func anonymous-methods