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

前端 未结 7 1507
别跟我提以往
别跟我提以往 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".

    0 讨论(0)
  • 2021-02-07 21:49

    lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:

     delegate(int i) { Console.WriteLine(i.ToString()) }
    

    can be replaced with

    f => Console.WriteLine(f.ToString())
    
    0 讨论(0)
  • 2021-02-07 21:50

    Lamda's are just syntactic sugar for delegates, they are not just inline, you can do the following:

    s.Find(a =>
    {
        if (a.StartsWith("H"))
            return a.Equals("HI");
        else
            return !a.Equals("FOO");
    });
    

    And delegates are still used when defining events, or when you have lots of arguments and want to actually strongly type the method being called.

    0 讨论(0)
  • 2021-02-07 21:51

    Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.

    0 讨论(0)
  • 2021-02-07 21:52

    Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:

    List<string> names = GetNames();
    names.ForEach(Console.WriteLine);
    
    1. it makes code more readable thus simple to understand.
    2. It makes code shorter thus less work for us ;)

    On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:

    1. Hard to understand for new developers
    2. Less object oriented
    3. Much harder to read

    So “does it mean we don’t have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.

    0 讨论(0)
  • 2021-02-07 21:54

    One not so big advantage for the older delegate syntax is that you need not specify the parameters if you dont use it in the method body. From msdn

    There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

    For example you can do:

    Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS
    

    While this fails:

    Action<int> a = => { }; //omitted parameter, doesnt compile.
    

    This technique mostly comes handy when writing event-handlers, like:

    button.onClicked += delegate { Console.WriteLine("clicked"); };
    

    This is not a strong advantage. It's better to adopt the newer syntax always imho.

    0 讨论(0)
提交回复
热议问题