Why use “new DelegateType(Delegate)”?

2019-01-15 08:53发布

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.

标签: c# delegates
5条回答
ゆ 、 Hurt°
2楼-- · 2019-01-15 08:53

Both are the same, but the latter syntax was added in C#2 to simplify delegate usage.

Both methods compile to the same byte code.

查看更多
Explosion°爆炸
3楼-- · 2019-01-15 09:13

Sometimes the correct type can't be deduced (like when you're calling a generic), in such a case you need to let the compiler know what kind of delegate you want.

Most of the time, though, naming the method group is easier and clearer.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-15 09:16

It's syntactic sugar. Ultimately both sets of code do the same thing.

I'd also note that .Net has a bunch of generic delegates built in that can save you alot of coding. In this case I'd do:

Action<string> writer;
writer = DelegateImplementer.StringWriter;
writer ("Hello");

This way you don't even need to create your own delegate.

查看更多
别忘想泡老子
5楼-- · 2019-01-15 09:17

The two are equivalent. The latter is syntax new with C# 2.0.

查看更多
再贱就再见
6楼-- · 2019-01-15 09:18

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.

查看更多
登录 后发表回答