C#委托实例化与刚好路过的方法引用化与、实例、方法

2023-09-02 01:37:36 作者:情义两难忘

我有一个简单的问题:什么是实例化一个C#的委托,而不是仅仅传递函数引用的优势在哪里?我的意思是:

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:

为什么:

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

当你可以做的:

Thread t = new Thread(SomeObject.SomeMethod);

双方将编制和工作在我的经验......我失去了一些东西?

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

推荐答案

只要方法组 SomeObject.SomeMethod 与返回类型的方法无效,并采取没有参数是没有区别的。这是因为的ThreadStart 定义为代理返回无效和不带任何参数,因此存在从方法组的隐式转换 SomeObject.SomeMethod 的ThreadStart 。因此,无论调用的过载 螺纹(的ThreadStart) 中的发的的构造。

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 .

语言规范的相关章节是6.6节(方法组转换)。

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

我有一个简单的问题:什么是实例化一个C#的委托,而不是仅仅传递函数引用的优势在哪里?

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();

someObject.SomeMethod 记的东西是一个方法组。你可以只把它看作一组重载方法可以使用​​符号 someObject.SomeMethod 是要抬头。

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.