检查泛型类型是否继承自泛型接口



我有一个基本接口,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用于查找任何通用接口 - 在此示例中,它过滤掉IReponse也由 GetInterfaces() 返回。

然后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<>))
  { }
}

最新更新