gpt4 book ai didi

c# - 以类为键的字典

转载 作者:太空狗 更新时间:2023-10-29 18:21:33 26 4
gpt4 key购买 nike

我正在学习电子工程,我是 C# 的初学者。我有测量数据,我想以二维方式存储它。我想我可以像这样制作一个 Dictionary:

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

这里的“Key”是我自己的类,有两个 int 变量。现在我想将数据存储在这个 Dictionary 中,但目前还行不通。如果我想用特殊键读取数据,错误报告说,该键在 Dictionary 中不可用。

这是类Key:

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;
}

为了测试它,我做了这样的东西:

获取元素:

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

取出元素:

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

有人有想法吗?

最佳答案

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

关于c# - 以类为键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46023726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com