Is there a case where delegate syntax is preferred over lambda expression for anonymous methods?

前端 未结 7 1642
别跟我提以往
别跟我提以往 2021-02-07 21:13

With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 21:49

    Yes there are places where directly using anonymous delegates and lambda expressions won't work.

    If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.

    public static void Invoke(Delegate d)
    {
      d.DynamicInvoke();
    }
    
    static void Main(string[] args)
    {
      // fails
      Invoke(() => Console.WriteLine("Test"));
    
      // works
      Invoke(new Action(() => Console.WriteLine("Test")));
    
      Console.ReadKey();
    }
    

    The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".

提交回复
热议问题