简体   繁体   中英

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.

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:

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> ). So, how can this be checked in the if?

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() )
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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