C#.是否可以使用具有基类型约束的静态泛型类,该基类型约束具有带有进一步基类型约束的方法

Sco*_*man 3 c# generics types constraints base

我希望能够创建一个基类型约束的静态泛型类型

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后添加另一种方法

...
    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;
    }
...
Run Code Online (Sandbox Code Playgroud)

由于HasIdAndParentId子类HasId满足约束条件T:HasId但编译器不接受方法的where基类型约束.

有任何想法吗?

Ben*_*n M 7

在这种情况下,您没有在方法上重新定义类型参数,因此您无法应用任何新约束.你应该能够这样做:

public static IEnumerable<T2> GetManyByParentId<T2>(
    ref List<T2> items, Guid parentId) 
    where T2 : T, HasIdAndParentId { .. } 
Run Code Online (Sandbox Code Playgroud)