2014-09-12 18 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()))