Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...