如何判断一个类是否实现了带有泛型类型的接口

3
我有以下代码:

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

}

现在我想知道提供程序是否使用反射实现了IProvider接口? 我不知道如何做到这一点。 我尝试了以下方法:
Provider test = new Provider();
var b = test.GetType().IsAssignableFrom(typeof(IProvider<IInput, IOutput>));

它返回false。

我需要帮助。我想避免使用类型名称(String)来解决这个问题。


我已经编辑了你的标题。请查看“问题标题应包含“标签”吗?”,在那里达成一致意见是“不应该包含”。 - John Saunders
3个回答

4

测试是否实现了它 全部 :

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

要查找什么,请使用FirstOrDefault而不是Any

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

0

首先,在定义中应该使用接口而不是类来声明IProvider

public interface IProvider<IInput, IOutput>
{

}

那么Provider类的定义应该是:

public class Provider: IProvider<IInput, IOutput>
{

}

最后,对于IsAssignableFrom的调用是反向的,应该是:

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

-1

我能够通过Mark的建议实现这一点。

以下是代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接