[英]How do I restrict the type of items added to a derived class?
I have DerivedClass which inherits from BaseClass. 我有DerivedClass,它继承自BaseClass。 I want to take advantage of the BaseCollection class which overrides the InsertItem method so I defined DerivedCollection and inherited from BaseCollection. 我想利用覆盖InsertItem方法的BaseCollection类,因此我定义了DerivedCollection并继承自BaseCollection。 The problem is, DerivedCollection allows both DerivedClass and BaseClass types to be added. 问题是,DerivedCollection允许添加DerivedClass和BaseClass类型。 I only want to permit DerivedClass types to be added to DerivedCollection. 我只想允许DerivedClass类型添加到DerivedCollection。 What am I missing? 我错过了什么?
public class BaseClass
{
public static string MyString;
}
public class BaseCollection<T> : Collection<BaseClass> where T : BaseClass
{
protected override void InsertItem(int index, BaseClass item)
{
throw new UnauthorizedAccessException("I'm sorry Dave, I'm afraid I can't do that.");
}
}
public class DerivedClass : BaseClass
{
public static int MyInteger;
}
public class DerivedCollection : BaseCollection<DerivedClass>
{
}
BaseCollection<T>
to inherit from Collection<T>
, not from Collection<BaseClass>
. 将BaseCollection<T>
更改为从Collection<T>
继承,而不是从Collection<BaseClass>
继承。 InsertItem
appropriately. 适当地更改InsertItem
参数。 public class BaseCollection<T> : Collection<T> where T : BaseClass
{
protected override void InsertItem (int index, T item)
{
throw new UnauthorizedAccessException("I'm sorry Dave, I'm afraid I can't do that.");
}
}
You only want to allow T: 你只想允许T:
protected override void InsertItem(int index, T item)
{
throw new UnauthorizedAccessException("I'm sorry Dave, I'm afraid I can't do that.");
}
You also have to inherit from Collection<T>
instead of Collection<BaseClass>
您还必须继承Collection<T>
而不是Collection<BaseClass>
You need to override InsertItem like so: 您需要像这样重写InsertItem:
public class DerivedCollection : BaseCollection<DerivedClass>
{
protected override void InsertItem(int index, DerivedClass item)
{
base.InsertItem(index, item);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.