c# - 匿名方法最短语法

标签 c# func anonymous-methods

关于匿名方法,并给出第一个参数作为 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/

相关文章:

c# - 使用 CSS 设置 GridView 格式

c# - 如何通过将 Func 和 Action 作为参数的函数的两个重载来简化代码?

delphi - 将匿名方法分配给接口(interface)变量或参数?

c# - C# 匿名函数中变量的作用域

reflection - 如何获取在 GO 中的 func() 参数中传递的参数值?

java - 匿名监听器是否与弱引用不兼容?

c# - 使用 TransactionScope 在一个事务中使用多个数据库(多个 DbContext)

c# - 在窗口打开之前设置窗口的Parent

c# - 如何在 nopCommerce 中为供应商和客户设置密码

c# - 创建排序 Func<IQueryable<T>、IOrderedQueryable<T>>?