代码之家  ›  专栏  ›  技术社区  ›  Scott Rickman

C。可以有一个静态泛型类,该类的基类型约束具有另一个基类型约束的方法

  •  3
  • Scott Rickman  · 技术社区  · 14 年前

    我希望能够创建一个带有基类型约束的静态泛型类型,比如

    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-base类型约束。

    有什么想法吗?

    3 回复  |  直到 14 年前
        1
  •  7
  •   Ben M    14 年前

    在本例中,您没有在方法上重新定义类型参数,因此不能应用任何新约束。您应该能够这样做:

    public static IEnumerable<T2> GetManyByParentId<T2>(
        ref List<T2> items, Guid parentId) 
        where T2 : T, HasIdAndParentId { .. } 
    
        2
  •  1
  •   LBushkin    14 年前

    使 GetManyByParentId 方法本身是泛型的,并将其泛型参数绑定到 T :

    public static IEnumerable<R> GetManyByParentId<R>(
                                        ref List<R> items, Guid parentId) 
           where R : T, HasIdAndParentId 
    
        3
  •  0
  •   Gebb    14 年前

    ben m的代码示例将不会编译,除非hasidandparentid是接口类型,而不是名为judjing的接口类型。

    使第二个方法本身成为泛型并使其依赖于其自身的类型参数(与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;
    }