我有继承自BaseClass的DerivedClass。我想利用重写InsertItem方法的BaseCollection类,因此我定义了DerivedCollection并从BaseCollection继承。问题是,DerivedCollection允许添加DerivedClass和BaseClass类型。我只想允许将DerivedClass类型添加到DerivedCollection中。我错过了什么?如何限制添加到派生类的项目类型?
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'不只限于'DerivedClass'或'DerivedCollection'。稍后,我可能会在'AnotherDerivedClass'和'AnotherDerivedCollection'和'AnotherDerivedCollection'中重复使用'BaseClass'和'BaseCollection'应该只允许'AnotherDerivedClass'类型。 – Hossy 2014-09-30 15:19:14
对不起 - 我误解了您的问题 - 更新了我的答案。 – Fordio 2014-09-30 15:19:49
嗯,那么我会不得不重写所有四个方法(ClearItems,InsertItem,RemoveItem和SetItem)来强制“DerivedClass”? – Hossy 2014-09-30 15:23:08