调用多态字段类事件 [英] Invocation of a polymorphic field-like event
问题描述
考虑以下代码:
public class TableMain {
public virtual event Action UpdateFilter;
....
}
public class TableSub : TableMain {
public override event Action UpdateFilter;
public void UpdateQuery() {
.....
if (UpdateFilter!=null) {
UpdateFilter(); // Invocation of polymorphic field-like event???
}
}
}
在此代码 ReSharper 显示警报调用多态字段类事件。
In this code ReSharper shows the alert "invocation of polymorphic field-like event".
我的问题是:
它实际上是什么意思?这是一个不好的编程实践的警戒吗?
另外,这是一个不好的做法来调用一个事件的多态吗? (知道一个事件只能从已经声明的类中提出)。
My question is: What does it actually mean? And is it an alert for a bad programming practice? Also, is it a bad practice to call an event polymorphically? (Knowing that an event can only be raised from the class which has declared it.)
推荐答案
嗯,你实际上已经这两个类似场景的事件。您的覆盖将覆盖添加/删除部分,但您将有两个字段 - 一个位于 TableMain
中,一个位于 TableSub
。只有 TableSub
中的一个将永远是非空的,除非该值在 TableMain
...中明确设置如果 TableMain
尝试提升事件本身,则不会像 TableSub
中那样调用相同的处理程序集。基本上,它会表现得奇怪。
Well, you've actually got two field-like events here. Your override will be overriding the add/remove part, but you'll have two fields - one in TableMain
and one in TableSub
. Only the one in TableSub
will ever be non-null, unless the value is set explicitly in TableMain
... so if TableMain
ever tries to raise the event itself, it won't call the same set of handlers as in TableSub
. Basically, it's going to behave strangely.
正确的方法是在 TableMain
中提供一个受保护的方法,以允许事件由子类引发:
The right approach is to provide a protected method in TableMain
to allow the event to be raised by subclasses:
protected void OnUpdateFilter()
{
Action handler = UpdateFilter;
if (handler != null)
{
handler();
}
}
然后使事件非虚拟,并删除覆盖 TableSub
。
Then make the event non-virtual, and remove the override in TableSub
.
请注意,事件签名与事件的常规约定不符 - 不使用 EventHandler
?
Note that your event signature doesn't match the normal convention for events - any reason for not using EventHandler
?
这篇关于调用多态字段类事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!