[英]How can I listen for events that are not implemented by all possible classes?
In my MEF-based application, some modules use forms, but some do not. 在基于MEF的应用程序中,有些模块使用表格,而有些则不使用表格。
I want to be able to respond to the closure of these forms, but can't seem to figure out how to do so. 我希望能够对这些表格的关闭做出回应,但似乎无法弄清楚该怎么做。 Module types are based on interfaces and those that use a form inherit a base class which inherits from Windows.Forms.Form
. 模块类型基于接口,而使用窗体的模块类型则继承自Windows.Forms.Form
的基类。
Eg 例如
public partial class SwatchForm : ModuleForm, IAcquisition
Where 哪里
public partial class ModuleForm : Form
Since not all things that inherit IAcquisition
(or my other module interfaces) inherit from ModuleForm
, I tried this: 由于并非所有继承IAcquisition
(或其他模块接口)的ModuleForm
都从ModuleForm
继承, ModuleForm
我尝试了以下方法:
if (this.AcquisitionModule.GetType().IsSubclassOf(typeof(ModuleForm)))
{
(ModuleForm)(this.AcquisitionModule).ModuleFormClosed += whatever....
}
But it still complains that IAcquisition
has nothing called ModuleFormClosed
. 但是它仍然抱怨IAcquisition
没有叫做ModuleFormClosed
。
I thought about using exceptions instead, but that feels like a bit of a hack. 我考虑过改用异常,但这感觉有点像hack。 Is there a way to do this using events? 有没有办法使用事件来做到这一点?
.
has a higher precedence than a cast, so you need to place the parentheses differently. 具有比强制转换更高的优先级,因此您需要以不同的方式放置括号。 Furthermore, you can check the type in a simpler way. 此外,您可以以更简单的方式检查类型。 Try 尝试
if (this.AcquisitionModule is ModuleForm) {
((ModuleForm) this.AcquisitionModule).ModuleFormClosed += ...
}
Another way is 另一种方法是
var moduleForm = this.AcquisitionModule as ModuleForm;
if (moduleForm != null) {
moduleForm.ModuleFormClosed += ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.