C# Delegate Instantiation vs. Just Passing the Method Reference [duplicate]
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!
精彩评论