[英]Test if class inherits generic interface
我知道有一些问题已经存在,但我似乎无法让这个工作。
我有一堂这样的课。
public class TopLocation<T> : ILocation
{
public string name { get; set; }
public string address { get; set; }
}
当我创建课程时,我指定它是IRestaurant
还是IClub
。 到目前为止没问题。
但是,如何在if
语句中测试它是IClub
还是IRestaurant
?
这失败了;
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{}
你可以这样做:
if (item.trendItem is TopLocation<IRestaurant>)
首先, ILocation
不是通用接口,因此尝试针对ILocation<T>
测试任何内容都将失败。 您的班级是通用类型。
其次,您试图确定用作通用类型的通用参数的类型是否是给定的接口。 为此,您需要获取该类型的通用类型参数,然后针对该类型执行检查:
var myInterfaceType = item.trendItem.GetType().GetGenericTypeArguments()[0];
if(myInterfaceType == typeof(ITopRestaurant))
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.