我希望能够创建具有基本类型约束的静态泛型类型,例如
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 基类型约束。
有任何想法吗?