C# 委托实例化与仅传递方法引用 [英] C# Delegate Instantiation vs. Just Passing the Method Reference

查看:29
本文介绍了C# 委托实例化与仅传递方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题:与仅传递函数引用相比,实例化 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 有一个返回类型为 void 的方法并且取不参数没有区别.这是因为 ThreadStart 被定义为返回 void 且不带参数的 delegate,因此存在来自方法组 SomeObject.SomeMethodThreadStart.因此,两者都调用了重载 Thread(ThreadStart)Thread 构造函数.

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.

这篇关于C# 委托实例化与仅传递方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆