简体   繁体   English

测试类是否继承通用接口

[英]Test if class inherits generic interface

I know there are a few questions on this already but I can't seem to get this to work. 我知道有一些问题已经存在,但我似乎无法让这个工作。

I have a class like this; 我有一堂这样的课。

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

When I create the class I specify whether it's an IRestaurant or IClub . 当我创建课程时,我指定它是IRestaurant还是IClub No problem so far. 到目前为止没问题。

However, how do I test to see whether it's an IClub or IRestaurant in an if statement? 但是,如何在if语句中测试它是IClub还是IRestaurant

This fails; 这失败了;

if (item.trendItem is ILocation<ITopRestaurant>)

and this returns null 这将返回null

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

The reason I'd like this in an if statement is because it's sitting within an ascx page in an MVC application and I am trying to render the correct partial view. 我在if语句中喜欢这个的原因是因为它位于MVC应用程序的ascx页面中,我正在尝试渲染正确的局部视图。

edit 编辑

in response to the comment; 回应评论;

public interface ITopClub{}
public interface ITopRestaurant { }
public interface ILocation{}

你可以这样做:

if (item.trendItem is TopLocation<IRestaurant>) 

First of all, ILocation is not a Generic Interface so trying to test anything against ILocation<T> is going to fail. 首先, ILocation不是通用接口,因此尝试针对ILocation<T>测试任何内容都将失败。 Your class is the Generic Type. 您的班级是通用类型。

Second, you're trying to figure out if the type used as a generic argument to your Generic Type is a given interface. 其次,您试图确定用作通用类型的通用参数的类型是否是给定的接口。 To do that, you need to get the Generic Type Arguments for the type and then perform the check against that type: 为此,您需要获取该类型的通用类型参数,然后针对该类型执行检查:

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

if(myInterfaceType == typeof(ITopRestaurant))
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM