2017-09-03 71 views
1

我正在學習電子工程,我是一個初學者在C#。我有測量數據,並希望以2維方式存儲它。我以爲我可以做這樣的字典:c#字典與類作爲密鑰

Dictionary<Key, string>dic = new Dictionary<Key, string>(); 

「關鍵」在這裏是一個自己的類與兩個int變量。現在我想將這些數據存儲在這個字典中,但目前爲止還不行。如果我想用特殊的密鑰讀取數據,錯誤報告說,密鑰在第一個字典中不可用。

這裏的鍵類:

public partial class Key 
{ 
    public Key(int Bahn, int Zeile) { 
    myBahn = Bahn; 
    myZeile = Zeile; 

} 
    public int getBahn() 
    { 
     return myBahn; 
    } 
    public int getZeile() 
    { 
     return myZeile; 
    } 
    private int myBahn; 
    private int myZeile; 
} 

測試它,我做這樣的事情:

獲得elemets在:

Key KE = new Key(1,1); 
dic.Add(KE, "hans"); 
... 

獲取elemets日期:

Key KE = new Key(1,1); 
monitor.Text = dic[KE]; 

有人有想法嗎?

+0

爲什麼不使用字符串作爲鍵?你究竟想要在字典中存儲什麼?你能解釋一下用例嗎? –

+0

是的。我有來自3D房間掃描儀的數據。掃描儀有兩個軸。我想根據兩個軸的位置來存儲信息。所以,如果Axis one位於15位,Axis two位於30位,我希望獲得密鑰:15,30 –

+0

並且您在字符串值中存儲什麼? –

回答

2

您需要在自己的類中覆蓋方法GetHashCodeEquals以將其用作關鍵字。

class Foo 
{ 
    public string Name { get; set;} 
    public int FooID {get; set;} 
    public override int GetHashCode()    
    { 
      return FooID; 
    } 
    public override bool Equals(object obj) 
    { 
      return Equals(obj as Foo); 
    } 

    public bool Equals(Foo obj) 
    { 
      return obj != null && obj.FooID == this.FooID; 
    } 
} 
+0

好的,你能給我一個例子嗎? –

+0

爲我的回答添加了一個示例 –

+0

謝謝。但我無法在我的課堂上實現它..你能解釋一下如果我覆蓋這些方法會發生什麼嗎?如果你在Foo類中有兩個int變量,它將會如何?如: Foo類 { public int Name {get;設置;} public int FooID {get;設置;} –