2014-09-12 23 views
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 ..

我需要这方面的帮助。我想避免使用类型名称(字符串)来解决这个问题。

+0

我编辑了自己的冠军。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 – 2014-09-12 20:37:48

回答

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

我能做到这一点使用马克的建议。

下面的代码:

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