c#字典与类作为密钥

问题描述:

我正在学习电子工程,我是一个初学者在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

并且您在字符串值中存储什么? –

您需要在自己的类中覆盖方法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;设置;} –