2012-11-20 117 views
2

我對C#相當陌生,所以如果這是一個愚蠢的問題,請原諒我。我遇到了一個錯誤,但我不知道如何解決它。我使用Visual Studio 2010中無法找到類型或名稱空間名稱keyedcollection

這行代碼

public class GClass1 : KeyedCollection<string, GClass2> 

給我的錯誤

'GClass1' does not implement inherited abstract member 'System.Collections.ObjectModel.KeyedCollection<string,GClass2>.GetKeyForItem(GClass2)' 

從我讀過這可以通過實現在抽象成員來解決繼承類像這樣

public class GClass1 : KeyedCollection<string, GClass2> 
{ 
    public override TKey GetKeyForItem(TItem item); 
    protected override void InsertItem(int index, TItem item) 
    { 
    TKey keyForItem = this.GetKeyForItem(item); 
    if (keyForItem != null) 
    { 
     this.AddKey(keyForItem, item); 
    } 
    base.InsertItem(index, item); 
} 

但是,這給了我錯誤,說'的類型或命名空間nam e找不到TKey/TItem找不到。'

幫助!

回答

4

TKeyTItemKeyedCollection<TKey, TItem>的類型參數。

既然你從KeyedCollection<string, GClass2>與具體類型分別stringGClass2繼承,你應該使用這兩種類型來替換佔位符類型TKeyTItem在您的實現:

public class GClass1 : KeyedCollection<string, GClass2> 
{ 
    public override string GetKeyForItem(GClass2 item); 
    protected override void InsertItem(int index, GClass2 item) 
    { 
    string keyForItem = this.GetKeyForItem(item); 
    if (keyForItem != null) 
    { 
     this.AddKey(keyForItem, item); 
    } 
    base.InsertItem(index, item); 
} 
+0

那偉大工程。但是又出現了另一個錯誤。這次它與之前的「修復」有關。我忘了GetKeyForItem是受保護的。新錯誤告訴我,當重寫System.Collections.ObjectModel.KeyedCollection .GetKeyForItem(GClass2) – user1839542

+0

時,我無法更改訪問修飾符。你應該也可以實現'GetKeyForItem()' - 我剛剛意識到沒有任何實現(從你的示例代碼中獲取)...... – BoltClock

相關問題