检查通用类型是否从通用接口继承

时间:2019-01-31 20:57:38

标签: c# .net generics inheritance 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))

感谢您的反馈。

2 个答案:

答案 0 :(得分:3)

由于您没有T反射的任何实例,因此必须使用。

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

IsGenericType用于查找任何通用接口-在此示例中,它过滤出IReponse,它也由GetInterfaces()返回。

然后GetGenericTypeDefinitionICollectionResponse<Employee>移到ICollectionResponse<>,这是我们要检查的类型。因为我们不知道Employee是什么。

如评论中所指出,可能实现了多个接口,例如ICollectionResponse<Employee>, ICollectionResponse<Person>。上面的代码将运行“ Do Something”语句,而不管是否存在一个或多个匹配项。在不了解更多范围的情况下不能说这是否是一个问题。

答案 1 :(得分:0)

这对您有用吗?

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

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