C# Object.GetHashCode() 方法及示例


C# 中的 Object.GetHashCode() 方法用作預設雜湊函式。

語法

public virtual int GetHashCode ();

示例

下面看一個示例 -

 演示

using System;
public class Demo {
   public static void Main() {
      Object ob = new Object();
      String str = "Jim";
      Type type1 = ob.GetType();
      Type type2 = str.GetType();
      Console.WriteLine("Hash Code = "+type1.GetHashCode());
      Console.WriteLine("Hash Code = "+type2.GetHashCode());
   }
}

輸出

Hash Code =30015890
Hash Code =21083178

示例

下面看另一個示例

using System;
public struct Value {
   private int v1;
   private int v2;
   private int v3;
   public Value(int v1, int v2, int v3) {
      this.v1 = v1;
      this.v2 = v2;
      this.v3 = v3;
   }
   public override int GetHashCode() {
      return Tuple.Create(v1, v2, v3).GetHashCode();
   }
}
public class Demo {
   public static void Main() {
      Value v = new Value(1, 7, 12);
      Console.WriteLine(v.GetHashCode());
      v = new Value(12, 8, 7);
      Console.WriteLine(v.GetHashCode());
      v = new Value(8, 7, 12);
      Console.WriteLine(v.GetHashCode());
   }
}

輸出

將生成以下輸出 -

1258
12803
8931

更新於: 03-Dec-2019

971 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.