[英]How to pass to a generic function class type that implements certan interface?
[英]How to Tell if a Class implements an interface with a generic type
我有以下代码:
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>
{
}
现在我想知道Provider是否使用反射实现IProvider? 我不知道该怎么做。 我尝试了以下方法:
Provider test = new Provider();
var b = test.GetType().IsAssignableFrom(typeof(IProvider<IInput, IOutput>));
它返回false ..
我需要帮助。 我想避免使用Type Name(String)来解决这个问题。
为了测试是否实现了它在所有 :
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]
// ...
}
首先, IProvider
应该使用接口而不是定义中的类来声明:
public interface IProvider<IInput, IOutput>
{
}
那么Provider
类的定义应该是:
public class Provider: IProvider<IInput, IOutput>
{
}
最后,对IsAssignableFrom
的调用是向后的,它应该是:
var b = typeof(IProvider<IInput, IOutput>).IsAssignableFrom(test.GetType());
我用Mark的建议就能做到这一点。
这是代码:
(type.IsGenericType &&
(type.GetGenericTypeDefinition() == (typeof(IProvider<,>)).GetGenericTypeDefinition()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.