匿名方法最短语法

时间:2014-09-03 19:29:49

标签: c# func anonymous-methods

关于匿名方法,并给出一种方法" WriteConditional"将第一个参数作为Func,有没有办法消除额外的"()=> "语法?

似乎你应该能够,因为只要没有额外的重载可以接受字符串,它是明确的,对吧?

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));
}

2 个答案:

答案 0 :(得分:2)

没有,没有这种方式。但是,你可以欺骗并提供自己的超载:

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);
}

答案 1 :(得分:0)

is there a way to even eliminate the extra "() => " syntax?

我也认为答案是否定的,但如果你的func通过使用运算符重载返回自定义类,你可以做一些事情。
如果您可以使用扩展方法

的操作重载,则可以对其他类型进行此操作
using System;

public class MyClass
{
   public static implicit operator Func<MyClass>(MyClass obj)
   {
     return () => { Console.WriteLine("this is another cheat"); return new MyClass(); };
   }
}


public class Program
{
   static void Main(string[] args)
   {

      MyClass x = new MyClass();
      WriteConditional(x);
      Console.ReadLine();
   }

   static void WriteConditional(Func<MyClass> retriever) {  }

}