[英]C#. Is is possible to have a static generic class with a base type constraint that has a method with a further base type constraint
I'd like to be able to create a static generic type with a base type constraint like 我希望能够创建一个基类型约束的静态泛型类型
public static class Manager<T> where T : HasId
{
public static T GetSingleById(ref List<T> items, Guid id)
{
// the Id is a property provided by HasId
return (from i in items where i.Id == id select i).SingleOrDefault();
}
}
Then add another method 然后添加另一种方法
...
public static IEnumerable<T> GetManyByParentId(ref List<T> items, Guid parentId) where T : HasIdAndParentId
{
// the parentId is a property of HasIdAndParentId which subclasses HasId
return from i in items where i.ParentId == parentId select i;
}
...
Since HasIdAndParentId subclasses HasId the constraint T : HasId is met but the compiler won't accept the where base type constraint on the method. 由于HasIdAndParentId子类HasId满足约束条件T:HasId但编译器不接受方法的where基类型约束。
Any ideas? 有任何想法吗?
In this case, you're not redefining the type parameter on the method, so you can't apply any new constraints. 在这种情况下,您没有在方法上重新定义类型参数,因此您无法应用任何新约束。 You should be able to do it this way:
你应该能够这样做:
public static IEnumerable<T2> GetManyByParentId<T2>(
ref List<T2> items, Guid parentId)
where T2 : T, HasIdAndParentId { .. }
Make the GetManyByParentId
method itself generic, and tie it's generic parameter to T
: 使
GetManyByParentId
方法本身是通用的,并将其通用参数绑定到T
:
public static IEnumerable<R> GetManyByParentId<R>(
ref List<R> items, Guid parentId)
where R : T, HasIdAndParentId
Ben M's code sample will not compile unless HasIdAndParentId is an interface type, which it is not, judjing by the name. Ben M的代码示例将不会编译,除非HasIdAndParentId是一个接口类型,它不是,由名称判断。
Making the second method itself generic and making it depending on its own type parameter (distinct from T) will provide you the desired constraint. 使第二个方法本身具有通用性并使其依赖于自己的类型参数(与T不同)将为您提供所需的约束。
public static IEnumerable<T1> GetManyByParentId<T1>(ref List<T1> items, Guid parentId) where T1 : HasIdAndParentId
{
// the parentId is a property of HasIdAndParentId which subclasses HasId
return from i in items where i.ParentId == parentId select i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.