2011-12-16 51 views
1

我知道這方面有幾個問題,但我似乎無法得到它的工作。測試類是否繼承了通用接口

我有這樣的課;

public class TopLocation<T> : ILocation 
{ 
    public string name { get; set; } 
    public string address { get; set; } 
} 

當我創建我指定它是一個IRestaurantIClub類。到目前爲止沒有問題。

但是,如何測試語句中的IClubIRestaurant

失敗;

if (item.trendItem is ILocation<ITopRestaurant>) 

,並返回null

   Type myInterfaceType = item.trendItem.GetType().GetInterface(
        typeof(ITopRestaurant).Name); 

我想這在if聲明的原因是因爲它在MVC應用程序坐在一個ASCX頁面中,我試圖呈現部分正確視圖。

編輯

響應註釋;

所有的
public interface ITopClub{} 
public interface ITopRestaurant { } 
public interface ILocation{} 
+1

有一個通用的`ILocation`以及?什麼是層次結構?什麼是「ITopRestaurant」? – Jon 2011-12-16 02:34:08

+0

ITopRestaunt只是一個空接口,用於識別此項目的ILocation類型 – griegs 2011-12-16 02:35:12

+0

可能的重複http://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific -generic-interface-type – HackedByChinese 2011-12-16 02:36:11

回答

2

你可以簡單地這樣做:

if (item.trendItem is TopLocation<IRestaurant>) 
1

首先,ILocation不是通用接口,從而試圖測試得罪ILocation<T>是要失敗的。你的課是通用類型。

其次,你想知道用作泛型類型的泛型參數的類型是否是給定的接口。要做到這一點,你需要獲得泛型類型參數的類型,然後針對該類型進行檢查:

var myInterfaceType = item.trendItem.GetType().GetGenericTypeArguments()[0]; 

if(myInterfaceType == typeof(ITopRestaurant)) 
{ 

}