我有多个课程(为了解释目的而简化):
public class A : BaseClass,
IHandleEvent<Event1>,
IHandleEvent<Event2>
{
}
public class B : BaseClass,
IHandleEvent<Event3>,
IHandleEvent<Event4>
{
}
public class C : BaseClass,
IHandleEvent<Event2>,
IHandleEvent<Event3>
{
}
在我的“BaseClass”中,我有一个方法,我想检查子类是否实现了特定事件的
IHandleEvent
。
public void MyMethod()
{
...
var event = ...;
...
// If this class doesn't implement an IHandleEvent of the given event, return
...
}
从this SO-answer我知道如何检查对象是否实现通用接口(实现
IHandleEvent<>
),如下所示:
if (this.GetType().GetInterfaces().Any(x =>
x.IsGenericType && x.GenericTypeDefinition() == typeof(IHandleEvent<>)))
{
... // Some log-text
return;
}
但是,我不知道如何检查对象是否实现特定通用接口(实现
IHandleEvent<Event1>
)。那么,如何在 if 中检查这一点呢?
只需使用
is
或 as
运算符:
if( this is IHandleEvent<Event1> )
....
或者,如果类型参数在编译时未知:
var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
....