具有一个字段(即整数)的结构 - 您是否仍需要重写 GetHashCode、Equals 等?
Struct with one field (i.e. integer) - do you still need to override GetHashCode, Equals, etc?
经常有人在谈论结构时,建议您覆盖Equals
、GetHashCode
等
如果您的 struct
只有一个 单个整数 (或任何其他 简单值类型 ,这是否也是必要的)?
比如说:
public struct LolCatId
{
public int Id { get; }
public LolCatId(int id)
{
Id = id;
}
}
在 HashSets
等中使用时 - 有什么需要考虑的吗?或者这是否会在所有情况下都能完美地发挥您对性能的期望?
你最好覆盖 Equals
和GetHashCode
因为值类型的默认等式成员通常基于反射(这就是为什么可以慢)。
一些默认的 Equals
实现非常 奇怪 ,例如:
// Wrong Equals optimization demo:
// .Net (4.7) doesn't use reflection here but compare bytes
// and this decision is incorrect in the context
struct MyDemo {
public double x;
}
...
byte[] bits = BitConverter.GetBytes(double.NaN);
bits[1] = 42;
// a holds "standard" NaN
MyDemo a = new MyDemo() { x = double.NaN };
// b holds "modified" NaN
MyDemo b = new MyDemo() { x = BitConverter.ToDouble(bits, 0)};
Console.Write(string.Join(Environment.NewLine,
$"Are structs equal? {(a.Equals(b) ? "Yes" : "No")}",
$"Are fields equal? {(a.x.Equals(b.x) ? "Yes" : "No")}"));
结果:
Are structs equal? No
Are fields equal? Yes
详情见
让我们站在安全的一边,尤其是当这两种方法都可以轻松实施时,例如在你的情况下:
public struct LolCatId {
public int Id { get; }
public LolCatId(int id) {
Id = id;
}
public override int GetHashCode() => Id;
public override bool Equals(object obj) =>
obj is LolCatId other ? other.Id == Id : false;
}
经常有人在谈论结构时,建议您覆盖Equals
、GetHashCode
等
如果您的 struct
只有一个 单个整数 (或任何其他 简单值类型 ,这是否也是必要的)?
比如说:
public struct LolCatId
{
public int Id { get; }
public LolCatId(int id)
{
Id = id;
}
}
在 HashSets
等中使用时 - 有什么需要考虑的吗?或者这是否会在所有情况下都能完美地发挥您对性能的期望?
你最好覆盖 Equals
和GetHashCode
因为值类型的默认等式成员通常基于反射(这就是为什么可以慢)。
一些默认的 Equals
实现非常 奇怪 ,例如:
// Wrong Equals optimization demo:
// .Net (4.7) doesn't use reflection here but compare bytes
// and this decision is incorrect in the context
struct MyDemo {
public double x;
}
...
byte[] bits = BitConverter.GetBytes(double.NaN);
bits[1] = 42;
// a holds "standard" NaN
MyDemo a = new MyDemo() { x = double.NaN };
// b holds "modified" NaN
MyDemo b = new MyDemo() { x = BitConverter.ToDouble(bits, 0)};
Console.Write(string.Join(Environment.NewLine,
$"Are structs equal? {(a.Equals(b) ? "Yes" : "No")}",
$"Are fields equal? {(a.x.Equals(b.x) ? "Yes" : "No")}"));
结果:
Are structs equal? No
Are fields equal? Yes
详情见
让我们站在安全的一边,尤其是当这两种方法都可以轻松实施时,例如在你的情况下:
public struct LolCatId {
public int Id { get; }
public LolCatId(int id) {
Id = id;
}
public override int GetHashCode() => Id;
public override bool Equals(object obj) =>
obj is LolCatId other ? other.Id == Id : false;
}