Why use quot;new DelegateType(Delegate)quot;?(为什么使用“new DelegateType(Delegate)?)
问题描述
好的,假设您在某个类中定义了一个委托.
Ok, suppose you define a delegate in some class.
public delegate void StringDelegate (string s);
另一个类实现了一个方法:
and another class implements a method :
public static void StringWriter (string s) {...}
在我正在阅读Programming C#"第 4 版的书中,他们使用 new 关键字创建委托,例如:
In the book that I'm reading "Programming C#" 4th ed they create delegates using the new keyword, ex:
ClassDelegate.StringDelegate writer;
writer = new ClassDelegate.StringDelegate (DelegateImplementer.StringWriter);
writer("Hello");
不过,我看到也可以这样调用委托方法
However, I see one can also call the delegate method this way
ClassDelegate.StringDelegate writer;
writer = DelegateImplementer.StringWriter;
writer ("Hello");
有什么区别?当我可以简单地传递或引用方法委托的签名时,为什么还要实例化并创建一个对象委托.
What's the difference? Why do I want instantiate and create an object delegate when I can just simply pass or make reference to the signature of the method delegate.
推荐答案
这两种说法绝对没有区别.writer = DelegateImplementer.StringWriter;
仍然创建一个 delegate
对象;编译器将为您生成 new ClassDelegate.StringDelegate ()
.这只是 在 C# 2.0 中添加的更简洁的语法.
There is absolutely no difference between the two statements. writer = DelegateImplementer.StringWriter;
still creates a delegate
object; the compiler will generate the new ClassDelegate.StringDelegate ()
for you. It's just a cleaner syntax that was added in C# 2.0.
正如@Ben Voigt 在他的回答中提到的,只有在使用 Control.Invoke() 例如.
As @Ben Voigt mentioned in his answer is only required in C# 2.0 where the compiler can't deduce the type of the delegate, when using Control.Invoke() for example.
这篇关于为什么使用“new DelegateType(Delegate)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么使用“new DelegateType(Delegate)"?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01