为什么要使用“new DelegateType(Delegate)”? [英] Why use "new DelegateType(Delegate)"?

查看:151
本文介绍了为什么要使用“new DelegateType(Delegate)”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,假设你在某个类中定义一个委托。

  public delegate void StringDelegate(string s); 

另一个类实现了一个方法:

  public static void StringWriter(string s){...} 

在我正在阅读的编程C#第4版中,他们使用新的关键字创建代表,例如:

  ClassDelegate.StringDelegate writer; 
writer = new ClassDelegate.StringDelegate(DelegateImplementer.StringWriter);
writer(Hello);

但是,我看到一个也可以这样调用委托方法

  ClassDelegate.StringDelegate writer; 
writer = DelegateImplementer.StringWriter;
writer(Hello);

有什么区别?为什么要实例化并创建一个对象委托,当我只是简单地传递或引用方法委托的签名。

解决方案

这两个语句绝对没有区别。 writer = DelegateImplementer.StringWriter; 仍然创建一个委托对象;编译器将为您生成新的ClassDelegate.StringDelegate() 。它只是一个更干净的语法是添加到C#2.0



由于@Ben Voigt在答案中提到,只需要在C#2.0中,编译器无法推断代表的类型,当使用< a href =http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx =noreferrer> Control.Invoke()例如。


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) {...}

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.

解决方案

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.

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)”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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