开发者

C# Delegate Instantiation vs. Just Passing the Method Reference [duplicate]

开发者 https://www.devze.com 2022-12-19 08:41 出处:网络
This question already has answers here: 开发者_开发技巧 Difference between wiring events with and without "new"
This question already has answers here: 开发者_开发技巧 Difference between wiring events with and without "new" (6 answers) What is the difference between Events with Delegate Handlers and those without? [duplicate] (4 answers) Closed last year.

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:

Thread t = new Thread(new ThreadStart(SomeObject.SomeMethod));

When you can do:

Thread t = new Thread(SomeObject.SomeMethod);

Both will compile and work in my experience...am I missing something?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消