3

我希望能够创建具有基本类型约束的静态泛型类型,例如

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

有任何想法吗?

4

3 回答 3

7

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

public static IEnumerable<T2> GetManyByParentId<T2>(
    ref List<T2> items, Guid parentId) 
    where T2 : T, HasIdAndParentId { .. } 
于 2010-08-13T15:21:43.943 回答
1

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

public static IEnumerable<R> GetManyByParentId<R>(
                                    ref List<R> items, Guid parentId) 
       where R : T, HasIdAndParentId 
于 2010-08-13T15:20:06.807 回答
0

除非 HasIdAndParentId 是接口类型,否则 Ben M 的代码示例将无法编译,从名称来看,它不是。

使第二种方法本身具有通用性并使其依赖于其自己的类型参数(与 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;
}
于 2010-08-13T15:20:20.050 回答