检查对象是否实现了特定的通用接口 [英] Check if object implements specific generic interface

查看:46
本文介绍了检查对象是否实现了特定的通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个类(为了解释而简化):

I have multiple classes (simplified for explaining purposes):

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.

In my "BaseClass" I have a method where I want to check whether or not the Child-class implements an IHandleEvent of a specific event.

public void MyMethod()
{
    ...
    var event = ...;
    ...
    // If this class doesn't implement an IHandleEvent of the given event, return
    ...
}

来自这个 SO-answer 我知道如何检查对象是否实现了通用接口(实现了 IHandleEvent<>),如下所示:

From this SO-answer I know how to check if an object implements a generic interface (implements IHandleEvent<>), like this:

if (this.GetType().GetInterfaces().Any(x =>
    x.IsGenericType && x.GenericTypeDefinition() == typeof(IHandleEvent<>)))
{
    ... // Some log-text
    return;
}

但是,我不知道如何检查对象是否实现了特定的通用接口(实现了 IHandleEvent).那么,如何在 if 中进行检查?

But, I don't know how to check if an object implements a SPECIFIC generic interface (implements IHandleEvent<Event1>). So, how can this be checked in the if?

推荐答案

我们只需使用 isas 运算符:

Simply us the is or as operator:

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

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

Or, if the type argument isn't known at compile time:

var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
    ....

这篇关于检查对象是否实现了特定的通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆