2014-09-30 104 views
1

我有继承自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> 
{ 
} 

回答

2
    继承
  1. 更改BaseCollection<T>继承自Collection<T>,而不是从Collection<BaseClass>继承。
  2. 适当地更改参数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."); 
    } 
} 
0

你需要重写InsertItem像这样:

public class DerivedCollection : BaseCollection<DerivedClass> 
{ 
protected override void InsertItem(int index, DerivedClass item) 
    { 
     base.InsertItem(index, item); 
    } 
} 
+0

的问题是,'BaseCollection'不只限于'DerivedClass'或'DerivedCollection'。稍后,我可能会在'AnotherDerivedClass'和'AnotherDerivedCollection'和'AnotherDerivedCollection'中重复使用'BaseClass'和'BaseCollection'应该只允许'AnotherDerivedClass'类型。 – Hossy 2014-09-30 15:19:14

+0

对不起 - 我误解了您的问题 - 更新了我的答案。 – Fordio 2014-09-30 15:19:49

+0

嗯,那么我会不得不重写所有四个方法(ClearItems,InsertItem,RemoveItem和SetItem)来强制“DerivedClass”? – Hossy 2014-09-30 15:23:08

1

你只想让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>