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
您需要覆盖方法GetHashCode并Equals在您自己的类中将其用作键.
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)