检查对象是否实现特定的通用接口
Check if object implements specific generic interface
我有多个 classes(为解释目的而简化):
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" 中,我有一个方法可以检查 Child-class 是否实现了特定事件的 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;
}
但是,我不知道如何检查对象是否实现了 SPECIFIC 通用接口(实现 IHandleEvent<Event1>
)。那么,如何在 if 中进行检查?
只需我们 is
或 as
运算符:
if( this is IHandleEvent<Event1> )
....
或者,如果类型参数在编译时未知:
var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
....
我有多个 classes(为解释目的而简化):
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" 中,我有一个方法可以检查 Child-class 是否实现了特定事件的 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;
}
但是,我不知道如何检查对象是否实现了 SPECIFIC 通用接口(实现 IHandleEvent<Event1>
)。那么,如何在 if 中进行检查?
只需我们 is
或 as
运算符:
if( this is IHandleEvent<Event1> )
....
或者,如果类型参数在编译时未知:
var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
....