2017-06-02 56 views
1

我想定義一個自定義類型,只擴展DIctionary只有一個區別。當我設置一個這樣的值:C#自定義詞典類型與setter如果不存在鍵

myCustomDic[3.5] = 4.0; 

它首先檢查密鑰3.5是否存在。如果是,則將該值設置爲新值。否則它將添加新值的密鑰。我這樣做是這樣的:

class Dic : Dictionary<double, double> 
    { 
     private readonly Dictionary<double, double> _property; 
     public Dic(Dictionary<double, double> property) 
     { 
      _property = property; 
     } 
     //Indexer: 
     public new double this[double CA] 
     { 
      get 
      { 
       return _property[CA]; 
      } 
      set 
      { 
       if (_property.ContainsKey(CA)) 
       { 
        _property[CA] = value; 
       } 
       else 
       { 
        _property.Add(CA, value); 
       } 
      } 
     } 
    } 

,我使用它是這樣的:

var testDic = new Dic(new Dictionary<double, double>()); 
testDic[2.5] = 4.0; 

但是,有添加到testDic沒有鍵值對? 有人可以告訴爲什麼嗎?

回答

4

因爲您的子類爲Dictionary,所以您不需要自己的專用字典。此外,您所描述的行爲是如何Dictionary已經工作的,所以你並不需要在所有創建自己的類:在Dictionary<TKey, TValue>.Item Property (TKey)

var t2 = new Dictionary<double, double>(); 

t2[2.5] = 4.0; 
Console.WriteLine(t2[2.5]); // outputs 4 
t2[2.5] = 8.0; 
Console.WriteLine(t2[2.5]); // outputs 8 

從文檔:

當您設置的屬性值,如果密鑰位於Dictionary中,則與該密鑰關聯的值將被分配的值替換。如果密鑰不在「詞典」中,則鍵和值將添加到詞典中。

,但你可以:

class Dic : Dictionary<double, double> { 
    //Indexer: 
    public new double this[double CA] { 
     get => (this as Dictionary<double, double>)[CA]; 
     set { 
      var parent = this as Dictionary<double, double>; 
      if (parent.ContainsKey(CA)) 
       parent[CA] = value; 
      else 
       parent.Add(CA, value); 
     } 
    } 
} 

然後,你可以這樣做:

var testDic = new Dic(); 

testDic[2.5] = 4.0; 
Console.WriteLine(testDic[2.5]); // this outputs 4 
testDic[2.5] = 8.0; 
Console.WriteLine(testDic[2.5]); // this outputs 8 
0

這是因爲你檢查這仍然是零,因爲你沒有覆蓋它的Count屬性。

你的_property的數量會增加,但不是外部的。

調試器可視化工具仍然會調用原始的字典計數,該計數器仍然會報告0,但是如果您將其打印到控制檯,它將起作用。

我還是不明白你爲什麼從字典中派生出來,因爲你描述你的需求的方式已經被字典實現了。

public TValue this[TKey key] 
{ 
    get 
    { 
     int num = this.FindEntry(key); 
     if (num >= 0) 
     { 
      return this.entries[num].value; 
     } 
     ThrowHelper.ThrowKeyNotFoundException(); 
     return default(TValue); 
    } 
    set 
    { 
     this.Insert(key, value, false); 
    } 
}