I know about C# events and delegates. I find them incredibly useful for event-driven sub-systems. One thing I don't understand, however, is why all the .NET documentation for events uses a very specific pattern for delegates:
public class Foo
{
public class CustomEventArgs : System.EventArgs
{
...
}
public delegate void CustomEventHandler(object sender, EventArgs e);
public event CustomEventHandler CustomEvent;
public void OnCustomEvent(int x, float y, bool z)
{
if (CustomEvent != null)
CustomEvent(this, new CustomEventArgs(x, y, z));
}
}
I find this method of declaring and using delegates incredibly unsecure and clunky compared to using custom delegates. For example:
public class Foo
{
public delegate void CustomEventHandler(Foo foo, int x, float y, bool z);
public event CustomEventHandler CustomEvent;
public void OnCustomEvent(int x, int y, int z)
{
if (CustomEvent != null)
CustomEvent(this, x, y, z);
}
}
Besides the obvious advantage of "It's the pattern most familiar to .NET programmers", I fail to see any other practical advantages to using delegates with the void CustomEventHandler(object sender, CustomEventArgs e) signatures as opposed to custom delegates. Mainly, you have the following advantages with custom delegates:
- You can guarantee the sender is of a specific type.
- You don't need a whole new class just to pass the event data, leading to messier code and name pollution
I would be interested to know if there are any other advantages to using the .NET pattern for events and delegates that I might be missing.
Aucun commentaire:
Enregistrer un commentaire