2011-12-16 29 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)) 
{ 

}