C# 如何限制添加到派生类的项的类型?

C# 如何限制添加到派生类的项的类型?,c#,collections,derived-class,C#,Collections,Derived Class,我有一个从基类继承的DerivedClass。我想利用覆盖InsertItem方法的BaseCollection类,因此我定义了DerivedCollection并从BaseCollection继承。问题是,DerivedCollection允许添加DerivedClass和基类类型。我只想允许将DerivedClass类型添加到DerivedCollection。我错过了什么 public class BaseClass { public static string MyString;

我有一个从基类继承的DerivedClass。我想利用覆盖InsertItem方法的BaseCollection类,因此我定义了DerivedCollection并从BaseCollection继承。问题是,DerivedCollection允许添加DerivedClass和基类类型。我只想允许将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>
{
}
公共类基类
{
公共静态字符串MyString;
}
公共类BaseCollection:集合,其中T:BaseCollection
{
受保护的重写void插入项(int索引,基类项)
{
抛出新的UnauthorizedAccessException(“对不起,Dave,恐怕我不能这么做。”);
}
}
公共类派生类:基类
{
公共静态整数;
}
公共类DerivedCollection:BaseCollection
{
}

您需要覆盖插入项,如下所示:

public class DerivedCollection : BaseCollection<DerivedClass>
{
protected override void InsertItem(int index, DerivedClass item)
    {
        base.InsertItem(index, item);
    }
}
公共类DerivedCollection:BaseCollection
{
受保护的重写void插入项(int索引,DerivedClass项)
{
基本插入项(索引,项目);
}
}

您只想允许T:

protected override void InsertItem(int index, T item)
{
    throw new UnauthorizedAccessException("I'm sorry Dave, I'm afraid I can't do that.");
}
您还必须从
集合
继承,而不是从
集合

  • BaseCollection
    更改为从
    Collection
    继承,而不是从
    Collection
    继承
  • 适当更改插入项的参数
  • 公共类BaseCollection:集合,其中T:BaseCollection
    {
    受保护的覆盖无效插入项(int索引,T项)
    {
    抛出新的UnauthorizedAccessException(“对不起,Dave,恐怕我不能这么做。”);
    }
    }
    
    问题在于
    BaseCollection
    不是
    DerivedClass
    DerivedCollection
    所独有的。稍后,我可能会在
    另一个派生类
    另一个派生类
    中重用
    BaseClass
    另一个派生类
    另一个派生类
    只允许
    另一个派生类
    类型。啊,那么我必须重写这四个方法吗(ClearItems、InsertItem、RemoveItem和SetItem)只是为了强制
    DerivedClass
    ?事实上,@Dennis_E已经找到了您在上面寻找的答案。您需要按照他的指示更改BaseCollection。
    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.");
        }
    }