2014-09-30 39 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>