简体   繁体   English

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

[英]Check if object implements specific generic interface

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>
{
}

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. 在我的“ BaseClass”中,我有一个方法要检查Child-class是否实现特定事件的IHandleEvent

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

From this SO-answer I know how to check if an object implements a generic interface (implements IHandleEvent<> ), like this: 这个SO-answer中,我知道如何检查对象是否实现了通用接口(实现IHandleEvent<> ),如下所示:

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

But, I don't know how to check if an object implements a SPECIFIC generic interface (implements IHandleEvent<Event1> ). 但是,我不知道如何检查对象是否实现了SPECIFIC通用接口(实现IHandleEvent<Event1> )。 So, how can this be checked in the if? 那么,如何在if中检查呢?

Simply us the is or as operator: 只需我们的isas运算符:

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

Or, if the type argument isn't known at compile time: 或者,如果在编译时不知道type参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM