简体   繁体   中英

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 . No problem so far.

However, how do I test to see whether it's an IClub or IRestaurant in an if statement?

This fails;

if (item.trendItem is ILocation<ITopRestaurant>)

and this returns 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.

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. 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))
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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