C#-子类类型列表
我想要一个类类型列表(不是类实例列表),其中列表中的每个成员都是MyClass的子类 例如,我可以这样做:C#-子类类型列表,c#,list,class,generics,types,C#,List,Class,Generics,Types,我想要一个类类型列表(不是类实例列表),其中列表中的每个成员都是MyClass的子类 例如,我可以这样做: List<System.Type> myList; myList.Add(typeof(mySubClass)); 列出myList; Add(typeof(mySubClass)); 但是我想限制列表只接受MyClass的子类 这与问题不同。 理想情况下,我希望避免使用linq,因为它目前未在我的项目中使用。,并且:。因此,这是一个很好的选择: public class
List<System.Type> myList;
myList.Add(typeof(mySubClass));
列出myList;
Add(typeof(mySubClass));
但是我想限制列表只接受MyClass的子类
这与问题不同。
理想情况下,我希望避免使用linq,因为它目前未在我的项目中使用。,并且:。因此,这是一个很好的选择:
public class ListOfTypes<T>
{
private List<Type> _types = new List<Type>();
public void Add<U>() where U : T
{
_types.Add(typeof(U));
}
}
请注意:在第二个版本中,您仍然可以
Add(typeof(Foo))
您应该从list派生一个list类,并重写Add方法以执行所需的类型检查。我不知道在.NET中有什么方法可以自动做到这一点
类似这样的方法可能会奏效:
public class SubTypeList : List<System.Type>
{
public System.Type BaseType { get; set; }
public SubTypeList()
: this(typeof(System.Object))
{
}
public SubTypeList(System.Type baseType)
{
BaseType = BaseType;
}
public new void Add(System.Type item)
{
if (item.IsSubclassOf(BaseType) == true)
{
base.Add(item);
}
else
{
// handle error condition where it's not a subtype... perhaps throw an exception if
}
}
}
公共类子类列表:列表
{
public System.Type BaseType{get;set;}
公共子目录()
:this(typeof(System.Object))
{
}
公共子类型列表(System.Type baseType)
{
BaseType=BaseType;
}
公共新作废添加(System.Type项)
{
if(item.IsSubclassOf(BaseType)==true)
{
基础。添加(项目);
}
其他的
{
//处理非子类型的错误条件…如果
}
}
}
您需要更新向列表添加/更新项的其他方法(索引设置器、AddRange、Insert等)创建您自己的列表,该列表继承自列表并覆盖
add
方法。我认为您无法在编译时验证这一点。您可以创建自己的列表并添加。@dcg不允许您完成此操作,因为Add
不是虚拟的。你需要组成一个列表,而不是从中继承。我会避免继承,因为你也可以做Add(typeof(string))
。
public class ListOfTypes<T> : List<Type>
{
public void Add<U>() where U : T
{
Add(typeof(U));
}
}
public class SubTypeList : List<System.Type>
{
public System.Type BaseType { get; set; }
public SubTypeList()
: this(typeof(System.Object))
{
}
public SubTypeList(System.Type baseType)
{
BaseType = BaseType;
}
public new void Add(System.Type item)
{
if (item.IsSubclassOf(BaseType) == true)
{
base.Add(item);
}
else
{
// handle error condition where it's not a subtype... perhaps throw an exception if
}
}
}