简体   繁体   中英

How to Tell if a Class implements an interface with a generic type

I have the following code:

public interface IInput
{

}

public interface IOutput
{

}

public interface IProvider<Input, Output>
{

}

public class Input : IInput
{

}

public class Output : IOutput
{

}

public class Provider: IProvider<Input, Output>
{

}

Now I would like to know if Provider Implements IProvider using reflection? I don't know how to do this. I tried the following:

Provider test = new Provider();
var b = test.GetType().IsAssignableFrom(typeof(IProvider<IInput, IOutput>));

It returns false..

I need help with this. I would like to avoid using Type Name (String) to figure this out.

To test if it implements it at all :

var b = test.GetType().GetInterfaces().Any(
    x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProvider<,>));

To find of what , use FirstOrDefault instead of Any :

var b = test.GetType().GetInterfaces().FirstOrDefault(
    x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProvider<,>));
if(b != null)
{
    var ofWhat = b.GetGenericArguments(); // [Input, Output]
    // ...
}

First the IProvider should be declared using interfaces not classes in its definition :

public interface IProvider<IInput, IOutput>
{

}

Then Provider class definition should be:

public class Provider: IProvider<IInput, IOutput>
{

}

And finally the call to IsAssignableFrom is backwards, it should be:

var b = typeof(IProvider<IInput, IOutput>).IsAssignableFrom(test.GetType());

I was able to achieve this using Mark's suggestion.

Here's the code:

(type.IsGenericType &&
                (type.GetGenericTypeDefinition() == (typeof(IProvider<,>)).GetGenericTypeDefinition()))

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