这个问题在这里已经有了答案:
Difference between wiring events with and without "new"
(6 个回答)
What is the difference between Events with Delegate Handlers and those without? [duplicate]
(4 个回答)
9 个月前关闭。
我有一个简单的问题:实例化 C# 委托(delegate)与仅传递函数引用相比有什么优势?我的意思是:
为什么:
Thread t = new Thread(new ThreadStart(SomeObject.SomeMethod));
什么时候可以做:
Thread t = new Thread(SomeObject.SomeMethod);
根据我的经验,两者都可以编译和工作......我错过了什么吗?
最佳答案
只要方法组SomeObject.SomeMethod
有一个返回类型为 void
的方法不带参数没有区别。这是因为 ThreadStart
被定义为 delegate
返回 void
并且不带任何参数,因此有来自方法组SomeObject.SomeMethod
的隐式转换至ThreadStart
.因此,两者都在调用重载 Thread(ThreadStart)
的Thread
构造函数。
语言规范的相关部分是§6.6(方法组转换)。
I have a simple question: what's the advantage of instantiating a C# delegate as opposed to just passing the function reference?
所以,这里只是对术语的更正。和
class MyObject {
public void SomeMethod() { }
}
MyObject someObject = new MyObject();
someObject.SomeMethod
所表示的东西是一个方法组。您可以将其视为可以使用符号 someObject.SomeMethod
查找的重载方法集。 .
关于C# 委托(delegate)实例化与仅传递方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2181282/