簡體   English   中英

檢查泛型類型是否從通用接口繼承

[英]Checking if Generic Type Inherits from Generic Interface

我有一個基本界面,IResponse ...

public interface IResponse
{
    int CurrentPage { get; set; }
    int PageCount { get; set; }
}

...一個通用接口ICollectionResponse,它繼承自基接口...

public interface ICollectionResponse<T> : IResponse
{
    List<T> Collection { get; set; }
}

...和一個類EmployeesResponse,它繼承自通用接口,隨后是基接口...

public class EmployeesResponse : ICollectionResponse<Employee>
{
    public int CurrentPage { get; set; }
    public int PageCount { get; set; }
    public List<Employee> Collection { get; set; }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我的問題在這里。 我有一個通用的任務方法,它返回一個基本接口的實例,IResponse。 在這個方法中,我需要確定T是否來自ICollectionResponse。

public class Api
{
    public async Task<IResponse> GetAsync<T>(string param)
    {
        // **If T implements ICollectionResponse<>, do something**

        return default(IResponse);
    }
}

我嘗試過所有版本的IsAssignableFrom()方法都沒有成功,包括:

typeof(ICollectionResponse<>).IsAssignableFrom(typeof(T))

我感謝任何反饋。

由於您沒有任何T反射實例必須使用。

if (typeof(T).GetInterfaces().Any(
  i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollectionResponse<>)))
{
  Console.WriteLine($"Do something for {param}");
}

IsGenericType用於查找任何通用接口 - 在此示例中,它過濾掉也由GetInterfaces()返回的IReponse

然后GetGenericTypeDefinitionICollectionResponse<Employee>移動到ICollectionResponse<> ,這是我們要檢查的類型。 因為我們不知道Employee是什么。

正如評論中指出的那樣,可能會實現多個接口,例如ICollectionResponse<Employee>, ICollectionResponse<Person> 上面的代碼將運行“Do Something”語句,並不關心是否有一個匹配或多個匹配。 在不了解更多范圍的情況下,不能說這是否是一個問題。

這對你有用嗎?

List<bool> list = new List<bool>();

foreach (var i in list.GetType().GetInterfaces())
{
  if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>))
  { }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM