检查对象是否实现特定的通用接口

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中检查?

Chr*_*ris 6

只需我们isas运营商:

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)