fab*_*lis 1 c# struct dictionary unity-game-engine
我使用自定义结构作为字典中的键:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用.containskey和getkey时,我得到的疯狂的垃圾回收分配数量为每帧数百万
我已经研究了这个问题,并且我知道这与结构的错误装箱有关,这是因为未实现IEquatable以及对equals()和getHashCode之类的某些方法的覆盖。
我已经看到了一些如何实现这些示例的示例,但是我仅找到了包含2个或3个变量的小型结构的示例,因为我的结构具有17个值,我不知道该如何实现此目标,因为我不了解哈希码的方式工作,如果有人可以引导我朝正确的方向前进,我将不胜感激,我应该在此结构中添加哪些内容以使其可用作字典键?
这里的关键是:
IEquatable<TV>(将通过“约束”调用而不是通过装箱调用)GetHashCode()在要比较的任何字段上使用合适的哈希函数实现Equals(TV)用与之对齐的相等性检查来实施GetHashCode()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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |