【发布时间】:2010-08-13 15:15:24
【问题描述】:
我希望能够创建具有基本类型约束的静态泛型类型,例如
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 基类型约束。
有什么想法吗?
【问题讨论】:
-
顺便说一句——在您的使用中,
ref关键字是不必要的。引用类型(即对象)总是通过引用传递;ref仅表示引用本身可以通过方法修改(例如通过设置新的List<T>)。 -
是的,我知道这个 Ben,但同时我想向我的其他开发人员清楚正在发生的事情,即传入的列表将被更改。
标签: c# generics types constraints base