关于匿名方法,并给出第一个参数作为 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));
}
最佳答案
不,没有这样的方法。但是,您可以作弊并提供自己的重载:
void WriteConditional(Func<string> retriever, string format)
{
var value = retriever();
if(string.IsNullOrEmpty(value)==false)
Console.WriteLine(string.Format(format,value));
}
void WriteConditional(string value, string format)
{
WriteConditional(() => value, format);
}
关于c# - 匿名方法最短语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25652279/