c#Dictionary,类为Key

Qui*_*aus 9 c# dictionary 2d class key

我正在学习电子工程,我是c#的初学者.我已经测量了数据,并希望以2个方式存储它.我以为我可以制作这样的字典:

Dictionary<Key, string>dic = new Dictionary<Key, string>(); 
Run Code Online (Sandbox Code Playgroud)

"Key"在这里是一个拥有两个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;
}
Run Code Online (Sandbox Code Playgroud)

为了测试它我做了这样的事情:

获得elemets:

Key KE = new Key(1,1);
dic.Add(KE, "hans");
...
Run Code Online (Sandbox Code Playgroud)

获得elemets:

Key KE = new Key(1,1);
monitor.Text = dic[KE];
Run Code Online (Sandbox Code Playgroud)

有人有想法吗?

Aks*_*hat 13

您需要覆盖方法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; 
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下,会调用object类中的GetHashCode和Equals方法,以将键与您在字典中搜索的值进行比较。这不会为您提供所需的结果,因为根据您的自定义类不会进行比较。当您覆盖这些方法时,可以自定义上述比较发生的方式。只需从GetHashCode中返回一个使对象唯一的值,然后在Equals中对类的所有属性进行相等性检查 (2认同)