簡體   English   中英

具有一個字段(即整數)的結構 - 您是否還需要覆蓋 GetHashCode、Equals 等?

[英]Struct with one field (i.e. integer) - do you still need to override GetHashCode, Equals, etc?

通常當有人談論結構時,建議您覆蓋EqualsGetHashCode等。

如果您有一個只有一個整數(或任何其他簡單值類型)的struct ,這也有必要嗎?

說即:

public struct LolCatId
{
    public int Id { get; }

    public LolCatId(int id)
    {
        Id = id;
    }
}

HashSets等中使用時 - 有什么需要考慮的,或者這是否會在所有情況下都按照您的預期完美運行?

您應該更好地覆蓋EqualsGetHashCode因為值類型的默認均衡成員通常是基於反射的(這就是為什么可能會很慢)。

一些默認的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

詳情見

https://blogs.msdn.microsoft.com/seteplia/2018/07/17/performance-implications-of-default-struct-equality-in-c/

讓我們安全一點,尤其是當兩種方法都可以輕松實現時,例如在您的情況下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM