猿问

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

我有一个基本接口,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))

我感谢任何反馈。


宝慕林4294392
浏览 121回答 2
2回答

猛跑小猪

由于您没有任何必须使用的反射实例。Tif (typeof(T).GetInterfaces().Any(&nbsp; i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollectionResponse<>))){&nbsp; Console.WriteLine($"Do something for {param}");}IsGenericType用于查找任何通用接口 - 在此示例中,它过滤掉了也由 返回的接口。IReponseGetInterfaces()然后从哪个是我们要检查的类型移动到哪个类型。因为我们不知道是什么。GetGenericTypeDefinitionICollectionResponse<Employee>ICollectionResponse<>Employee正如注释中指出的那样,可以实现多个接口,例如 .上面的代码将运行“做某事”语句,并且不关心是否有一个匹配项或多个匹配项。在不知道更多范围的情况下,不能说这是否是一个问题。ICollectionResponse<Employee>, ICollectionResponse<Person>

桃花长相依

这对你有用吗?List<bool> list = new List<bool>();foreach (var i in list.GetType().GetInterfaces()){&nbsp; if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>))&nbsp; { }}
随时随地看视频慕课网APP
我要回答