Kev*_*sen 0 c# generics implementation types interface
我有多个类(简化用于解释目的):
public class A : BaseClass,
IHandleEvent<Event1>,
IHandleEvent<Event2>
{
}
public class B : BaseClass,
IHandleEvent<Event3>,
IHandleEvent<Event4>
{
}
public class C : BaseClass,
IHandleEvent<Event2>,
IHandleEvent<Event3>
{
}
Run Code Online (Sandbox Code Playgroud)
在我的"BaseClass"中,我有一个方法,我想检查Child-class是否实现IHandleEvent
了特定事件.
public void MyMethod()
{
...
var event = ...;
...
// If this class doesn't implement an IHandleEvent of the given event, return
...
}
Run Code Online (Sandbox Code Playgroud)
从这个SO答案我知道如何检查对象是否实现了通用接口(implements IHandleEvent<>
),如下所示:
if (this.GetType().GetInterfaces().Any(x =>
x.IsGenericType && x.GenericTypeDefinition() == typeof(IHandleEvent<>)))
{
... // Some log-text
return;
}
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何检查对象是否实现了SPECIFIC通用接口(implements IHandleEvent<Event1>
).那么,如何在if中检查?
只需我们is
或as
运营商:
if( this is IHandleEvent<Event1> )
....
Run Code Online (Sandbox Code Playgroud)
或者,如果在编译时未知类型参数:
var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
....
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1060 次 |
最近记录: |