[英]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.