C# Delegate Instantiation vs. Just Passing the Method Reference

后端 未结 3 565
夕颜
夕颜 2020-12-02 00:00

I have a simple question: what\'s the advantage of instantiating a C# delegate as opposed to just passing the function reference? What I mean is:

Why do:

         


        
相关标签:
3条回答
  • 2020-12-02 00:29

    That's equivalent. Good introductory article on the subject: C# Delegates, Anonymous Methods, and Lambda Expressions – O My!

    0 讨论(0)
  • 2020-12-02 00:30

    The compiler will infer that when you typed the shorter code, you meant the longer code. There's no difference in the ultimate effect. If you want the clarity of the full constructor, you can put it in; if you want the brevity of just the method group, you can allow the compiler to infer the constructor. It's just a stylistic choice.

    0 讨论(0)
  • 2020-12-02 00:50

    As long as the method group SomeObject.SomeMethod has a method with return type void and taking no parameters there is no difference. This is because ThreadStart is defined as a delegate that returns void and takes no parameters and therefore there is an implicit conversion from the method group SomeObject.SomeMethod to ThreadStart. Thus, both are invoking the overload Thread(ThreadStart) of the Thread constructor .

    The relevant section of the language specification is §6.6 (Method group conversions).

    I have a simple question: what's the advantage of instantiating a C# delegate as opposed to just passing the function reference?

    So, just a correction of terminology here. With

    class MyObject {
        public void SomeMethod() { }
    }
    
    MyObject someObject = new MyObject();
    

    the thing denoted by someObject.SomeMethod is a method group. You can just think of it as the set of overloaded methods can that be looked up using the notation someObject.SomeMethod.

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