Why do .NET events have a sender parameter of type object and not of type T? [duplicate]
Possible Duplicates:
In a C# event handler, why must the "sender" parameter be an object? Event Signature in .NET — Using a Strong T开发者_运维知识库yped 'Sender'?
Why do all of the events in .NET have their first parameter as of type object
, and not of a generic type T
? Every time I have to get my sender, I have to typecast it to some more derived type. For example:
(Button)sender
Because the universal signature of event handler methods was invented long before generics were ever added to the language.
Using System.Object
was the logical choice in the days before generics, as it really was the most "generic" object available. All other objects ultimately derive from System.Object
, including controls, BCL classes, and user-defined classes, because it is at the root of the type hierarchy.
Strongly types senders don't work too well with inheritance hierarchies.
public class Base
{
public event EventHandler<Base,MyEventArgs> MyEvent;
}
public class Derived:Base
{
}
Now you want to subscribe on Derived
to MyEvent
. Your sender will only be Base
. One could work around this with new
, but that gets ugly.
The first reason is that this design pre-dates the introduction of generics.
But what do you think a generic approach would look like? In WinForms an OnClick event can be triggered by a Button as well as by a MenuItem. A MenuItem is not even a Control.
This event signature is used through-out the .NET library, so sender could really be anything, not just a Control or other GUI element. And the mos common class is ... System.Object
.
You will have to type-cast.
精彩评论