如何限制添加到派生类的项的类型
本文关键字:类型 派生 何限制 添加 | 更新日期: 2023-09-27 18:25:10
我有继承自BaseClass的DerivedClass。我想利用BaseCollection类,它覆盖InsertItem方法,所以我定义了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<T>
更改为从Collection<T>
继承,而不是从Collection<BaseClass>
继承 - 适当更改
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.");
}
}
您只想允许T:
protected override void InsertItem(int index, T item)
{
throw new UnauthorizedAccessException("I'm sorry Dave, I'm afraid I can't do that.");
}
您还必须从Collection<T>
而不是Collection<BaseClass>
继承
您需要覆盖InsertItem,如下所示:
public class DerivedCollection : BaseCollection<DerivedClass>
{
protected override void InsertItem(int index, DerivedClass item)
{
base.InsertItem(index, item);
}
}