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

问题描述 投票:0回答:1

我有多个课程(为了解释目的而简化):

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 中检查这一点呢?

c# generics types interface implementation
1个回答
9
投票

只需使用

is
as
运算符:

if( this is IHandleEvent<Event1> )
    ....

或者,如果类型参数在编译时未知:

var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
    ....
© www.soinside.com 2019 - 2024. All rights reserved.