gpt4 book ai didi

c# - 如何实现 Struct 用作​​字典键

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:23 25 4
gpt4 key购买 nike

我正在使用自定义结构作为字典中的键:


public struct TV
{
public int B;
public int BC;
public int P;
public int PO;
public int PC;
public int W;
public int WO;
public int WC;
public int R;
public int RO;
public int RC;
public int G;
public int GO;
public int GC;
public int GW;
public int GWO;
public int GWC;

public TV(int b, int bC, int p, int po, int pC, int w, int wo, int wC, int r, int ro, int rC, int g, int go, int gC, int gw, int gwo, int gwC)
{
B = b;
BC = bC;
P = p;
PO = po;
PC = pC;
W = w;
WO = wo;
WC = wC;
R = r;
RO = ro;
RC = rC;
G = g;
GO = go;
GC = gC;
GW = gw;
GWO = gwo;
GWC = gwC;
}

}

然而,当我使用 .containskey 和 getkey 时,我得到了疯狂数量的垃圾收集分配,每帧数以百万计

我研究了这个问题,我知道它与结构的不正确装箱有关,因为没有实现 IEquatable 并覆盖了一些方法,如 equals() 和 getHashCode。

我看过一些关于如何实现这些的例子,但我只找到了 2 或 3 个变量的小结构的例子,因为我的结构有 17 个值,我不知道应该如何实现它,因为我不知道了解哈希码的工作原理,如果有人能指导我正确的方向,我将不胜感激,我应该向该结构添加什么以使其可用作字典键?

最佳答案

这里的关键是:

  1. 实现IEquatable<TV> (它将通过“约束”调用调用,而不是通过装箱调用)
  2. 实现GetHashCode()在您想要比较的任何字段上使用合适的哈希函数
  3. 实现Equals(TV)GetHashCode() 对齐的相等性检查
  4. 实现Equals(object)作为=> obj is TV typed && Equals(typed);

这应该避免所有的装箱和反射。


这是一种实现方式:

public struct TV : IEquatable<TV>
{

public override string ToString() => nameof(TV);

public int B;
public int BC;
public int P;
public int PO;
public int PC;
public int W;
public int WO;
public int WC;
public int R;
public int RO;
public int RC;
public int G;
public int GO;
public int GC;
public int GW;
public int GWO;
public int GWC;

public TV(int b, int bC, int p, int po, int pC, int w, int wo, int wC, int r, int ro, int rC, int g, int go, int gC, int gw, int gwo, int gwC)
{
B = b;
BC = bC;
P = p;
PO = po;
PC = pC;
W = w;
WO = wo;
WC = wC;
R = r;
RO = ro;
RC = rC;
G = g;
GO = go;
GC = gC;
GW = gw;
GWO = gwo;
GWC = gwC;
}

public override bool Equals(object obj) => obj is TV other && Equals(other);

public bool Equals(TV other)
{
return B == other.B &&
BC == other.BC &&
P == other.P &&
PO == other.PO &&
PC == other.PC &&
W == other.W &&
WO == other.WO &&
WC == other.WC &&
R == other.R &&
RO == other.RO &&
RC == other.RC &&
G == other.G &&
GO == other.GO &&
GC == other.GC &&
GW == other.GW &&
GWO == other.GWO &&
GWC == other.GWC;
}

public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(B);
hash.Add(BC);
hash.Add(P);
hash.Add(PO);
hash.Add(PC);
hash.Add(W);
hash.Add(WO);
hash.Add(WC);
hash.Add(R);
hash.Add(RO);
hash.Add(RC);
hash.Add(G);
hash.Add(GO);
hash.Add(GC);
hash.Add(GW);
hash.Add(GWO);
hash.Add(GWC);
return hash.ToHashCode();
}
}

关于c# - 如何实现 Struct 用作​​字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58963888/

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