gpt4 book ai didi

c# - 使用 C# 结构作为字典键的最佳方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 22:57:01 25 4
gpt4 key购买 nike

我有一个 C# 结构,我将其用作标准字典集合中的键。我已经为它的 GetHashCode 和 Equals 编写了重写,但我有点不高兴 Equals 被赋予一个装箱对象而不是直接引用我的结构类型。

我可以做些什么来优化我对结构类型的字典的使用,以避免不必要的装箱操作?

(这不是过早的优化,而是完全合适的优化,非常感谢。)

最佳答案

你可以实现一个通用的比较器:

public class MyStructComparer : IEqualityComparer<MyStruct>
{
public bool Equals(MyStruct x, MyStruct y)
{
// ...
}
public int GetHashCode(MyStruct obj)
{
// ...
}
}

然后将其用于 dictionary constructor :

var myStructDict = new Dictionary<MyStruct, string>(new MyStructComparer());

另一种方法是实现 IEquatable<MyStruct> MyStruct ,例如:

public struct MyStruct: IEquatable<MyStruct>
{
public int Id;

public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is MyStruct && Equals((MyStruct)obj);
}

public bool Equals(MyStruct other)
{
return this.Id == other.Id;
}

public override int GetHashCode()
{
return this.Id;
}
}

然后可以使用默认构造函数初始化字典:

var myStructDict = new Dictionary<MyStruct, string>();

关于c# - 使用 C# 结构作为字典键的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45856528/

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