In C# could we imagine writing our own events without writing delegates?
I learned t开发者_运维技巧he object-oriented in Java. Now in develop in C#. This means that I never really understood the functioning of delagates but I know how to use them.
Lately I discovered this page http://java.sun.com/docs/white/delegates.html.
If Java is able to create event without delagates is it possible to do the same in C#? Could we imagine writing our own events without writing a single delegate?
(Question already asked in french here)
Yes, you could use a single-method interface instead of a delegate. You'd also need an implementation of the multi-cast nature of delegates, both in terms of add/remove and invoke. It would be tough to have a single class implementing multicast and also implementing Invoke
in a typesafe way, however, due to the interfaces having different numbers and types of parameters. You could have a bunch of them of course: Multicast<T>
, Multicast<T1, T2>
etc. (The same class would handle asynchronous execution too, probably.)
The other pain in the neck is that you could only implement the interface once per class, even if you wanted several different handlers - so you'd have a lot of nested classes.
There's little that's particularly magical about delegates - they're just a very useful abstraction, and with the syntactic sugar of lambda expressions, anonymous methods and expression trees, they're even nicer.
No, you can't do events in C# without delegates. In C#, events are defined as delegates:
An
event
is a member that enables a class or object to provide notifications. Anevent
is declared like a field except that the declaration includes anevent
keyword and the type must be a delegate type.
However, you could mimic events using the Observer pattern.
Microsoft's answer to Sun's White Paper is worth reading.
That's a pretty old document and look where it's gotten them. You can do the exact same thing in .NET if you want. All the "Java Way" is doing is taking advantage of inheritance. That's fine but for many the "function pointer" semantic is much more straightforward and less verbose.
Yes you can. You can use predefined delegates. (I'm not sure what's your level of experience and what are you really asking about)
Why on earth would you want to do that? I mean, if you have a rules engine, or commands that are more than just eventhandlers, then sure: You will want to implement an interface, because you will have state and behavior besides the actual piece of code you want to fire.
But if providing some code to fire when the event is raised, then there's no reason to not use delegates.
Delegates are thin abstractions over method/function pointers and as such they add very little overhead. And IMO, one should not add overhead just for the sake of it.
精彩评论