Event parameter; “sender as Object”, or “sender as

2019-06-15 10:57发布

When I write public events for my business objects, I've adapted the habit of always passing the instance as "sender as Object", in addition to additional specific parameters. I just asked myself now why am I not specifying the class?

So for you with more experience; Do you ever pass the distinct class as sender in an event? And if so, what are your decision criteria for when this is ok/not ok?

8条回答
干净又极端
2楼-- · 2019-06-15 11:33

It is not a binding on you to have such implementation. Its usually done because of the EventHandler delegate was designed with such prototype.

Its a simple guideline followed through Base Class Library. But sure you can make you own Parameters and implementations.

But remember if it is to be used by some developer other that you, he will need to know about such implementation. Its don for greater good and flexibility to use an event anywhere irrespective of class its used in.

If you define a Custom Prototype for event then i would suggest that you also define Custom Delegate that will ensure you will have catch an exception if proper type is not passed. (User will need to do an Explicit cast if required)

Like this:

public delegate void MyEventHandler( MyType sender, EventArgs e);

Then use it where required as:

this.MyEvent += new MyEventHandler(my_eventhandlerfunction);
查看更多
叛逆
3楼-- · 2019-06-15 11:37

Don't be extreme. EventHandler(object sender, EventArgs e) has an object sender so that we can use it in many circumstances. But it doesn't mean a strongly-typed sender is evil. A strongly-typed sender is useful when this delegate is not going to be widely used(like EventHandler) e.g.

public delegate void SaveHandler(Controller sender, EventArgs e);

Now other developers(or someone using your library) can recogonize that the sender have to be a Controller, and they will be glad not to code like this:

public void MySaveHandler(object sender, EventArgs arg)
{
   var controller = sender as Controller;
   if (controller != null)
   {
       //do something
   }
   else
   {
       //throw an exception at runtime? 
       //It can be avoided if sender is strongly-typed
   }
}

And you can even make it generic:

public delegate void SaveHandler<T>(T sender, EventArgs args) 
                                              where T: IController;

It's pure legal and good practice in C#. You should make clear what you want to do, and then choose the better way. Either of them is evil/bad.

查看更多
登录 后发表回答