一个多态场般的事件调用 [英] 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
覆盖
请注意您的活动签名不匹配事件的正常惯例 - 任何理由不使用事件处理程序
?
Note that your event signature doesn't match the normal convention for events - any reason for not using EventHandler
?
这篇关于一个多态场般的事件调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!