当我写我的业务对象的公共事件,我已经适应总是通过实例为发件人为对象中,除了额外的具体参数的习惯。刚才我问我自己现在的为什么我不能指定类?
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?
不要偏激。 事件处理程序(对象发件人,EventArgs五)
有一个对象发件人,使我们可以在许多情况下使用它。不过,这并不意味着一个强类型的发送者是邪恶的。强类型发件人是当这种委托是不会被广泛使用的有用(如事件处理程序
)例如:
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);
现在其他开发人员(或某人使用您的库)可以recogonize发送者的有无以的是控制器
,他们会高兴不至code是这样的:
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;
这是在C#中的纯法律和好的做法。你应该清楚你想做什么,然后做出更好的选择。无论他们是邪恶的/坏的。
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.