繁体   English   中英

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

[英]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

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

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();
    }
}

然后添加另一种方法

...
    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;
    }
...

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

有任何想法吗?

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

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

使GetManyByParentId方法本身是通用的,并将其通用参数绑定到T

public static IEnumerable<R> GetManyByParentId<R>(
                                    ref List<R> items, Guid parentId) 
       where R : T, HasIdAndParentId 

Ben M的代码示例将不会编译,除非HasIdAndParentId是一个接口类型,它不是,由名称判断。

使第二个方法本身具有通用性并使其依赖于自己的类型参数(与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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM