![](/img/trans.png)
[英]Problem implementing a generic method in a generic type which inherits from a non-generic interface
[英]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
。
然后GetGenericTypeDefinition
从ICollectionResponse<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.