I'm having some real confusion about events in c#... if I have this code in an interfa开发者_开发百科ce:
Event OnBeforeSaving(ByVal Sender As TEntity, ByVal EventArgs As CancelEventArgs)
How should it be in c#? When I run it through a converter it gives me this
event OnBeforeSavingEventHandler OnBeforeSaving;
delegate void OnBeforeSavingEventHandler(TEntity Sender, CancelEventArgs EventArgs);
I'm not sure if I understand what is going on... in my head the code should be combined. Is this correct?
event OnBeforeSaving(TEntity Sender, CancelEventArgs EventArgs);
I'm not sure if I understand what is going on... in my head the code should be combined. Is this correct?
No. In VB.NET, you can combine this on a single line. The Event keyword allows you to specify the full signature of the delegate type being handled.
In C#, however, you need to explicitly tell the event which type of delegate it will use. If it's not a standard delegate type, then you have to declare the delegate, as well. This is what your converter is doing for you.
That being said, in this case, this:
delegate void OnBeforeSavingEventHandler(TEntity Sender, CancelEventArgs EventArgs);
event OnBeforeSavingEventHandler OnBeforeSaving;
Probably should be replaced with this:
event EventHandler<CancelEventArgs> OnBeforeSaving;
This is because there is a built-in EventHandler<T>
type in the framework, that follows the suggested pattern for events, which specifies that the sender should be an System.Object, and the EventArgs should be a subclass of EventArgs. This is not quite the same as your VB.NET code, however, since you were restricting the sender to a TEntity
type.
Even better would be to use the built-in CancelEventHandler type:
event CancelEventHandler OnBeforeSaving;
This is basically identical to EventHandler<CancelEventArgs>
, but more expected, since there is a framework event handler type specifically for cancellation.
.Net requires events to be of a Delegate type.
The VB compiler will automatically create a delegate type; the C# compiler forces you to create it yourself.
event EventHandler<CancelEventArgs> OnBeforeSaving;
This line:
delegate void OnBeforeSavingEventHandler(TEntity Sender, CancelEventArgs EventArgs);
defines a new type called "OnBeforeSavingEventHandler". It is a delegate type, which defines a method call that takes TEntity and CancelEventArgs parameters and returns nothing.
This line:
event OnBeforeSavingEventHandler OnBeforeSaving;
declares a class member that is an event called "OnBeforeSaving". This event is of type "OnBeforeSavingEventHandler". Therefore, any objects that wish to subscribe to this event must have a method that is compatible with the "OnBeforeSavingEventHandler" delegate type.
精彩评论