[英]Check if generic parameter of a class implements an interface
我有一個以下泛型類:
public class SearchResult<T>
{
public int ResultCount { get; set; }
public IEnumerable<T> Result { get; set; }
}
我還有一個Bird
類,它實現了IFlyble
接口:
public class Bird : IFlyable
{
public void Fly() {}
}
public interface IFlyable
{
void Fly();
}
我還有一個類型為object
的變量res
。 如何檢查res
是否是SearchResult<IFlyable>
?
我這樣試試:
if (res.GetType().IsAssignableFrom(typeof(SearchResult<IFlyable>)))
{
///
}
這樣:
if(res is SearchResult<IFlyable>)
{
///
}
但它似乎不起作用。
您遇到的問題可能是由於SearchResult<Bird>
無法轉換為SearchResult<IFlyable>
因為SearchResult<T>
在T
是不變的。
C#只允許接口和委托中的泛型類型差異。 您需要定義一個ISearchResult<>
接口,該接口在其泛型類型中是協變的。
在您的情況下,如果可以接受T
僅用作輸出,則可以按如下方式定義此類接口:
public interface ISearchResult<out T>
{
int ResultCount { get; }
IEnumerable<T> Result { get; }
}
現在, ISearchResult<Bird>
是一個ISearchResult<IFlyable>
因為您已經為編譯器提供了足夠的信息,以便它可以驗證轉換實際上是否安全
您也可以使用反射來嘗試這個,它也可以工作,不需要創建另一個接口。
static void Main()
{
var sr = new SearchResult<Bird>();
Console.WriteLine(IsSearchResultIFlyable(sr.GetType())
? "sr is SearchResult<IFlyable>"
: "sr is Not SearchResult<IFlyable>");
Console.ReadLine();
}
public static bool IsSearchResultIFlyable(Type t)
{
if (!t.IsGenericType) return false;
if (t.GetGenericTypeDefinition() != typeof(SearchResult<>)) return false;
var gr = t.GetGenericArguments();
return gr.Length == 1 && typeof(IFlyable).IsAssignableFrom(gr[0]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.