ValueType.GetHashCode 方法

定义

返回此实例的哈希代码。

public:
 override int GetHashCode();
public override int GetHashCode ();
override this.GetHashCode : unit -> int
Public Overrides Function GetHashCode () As Integer

返回

一个 32 位带符号整数,它是此实例的哈希代码。

示例

以下示例演示如何 GetHashCode 由派生值类型替代 方法。

public ref struct Complex
{
public:
   double m_Re;
   double m_Im;
   virtual bool Equals( Object^ ob ) override
   {
      if ( dynamic_cast<Complex^>(ob) )
      {
         Complex^ c = dynamic_cast<Complex^>(ob);
         return m_Re == c->m_Re && m_Im == c->m_Im;
      }
      else
      {
         return false;
      }
   }

   virtual int GetHashCode() override
   {
      return m_Re.GetHashCode() ^ m_Im.GetHashCode();
   }
};
public struct Complex
{
    public double m_Re;
    public double m_Im;

    public override bool Equals( object ob ){
        if( ob is Complex ) {
            Complex c = (Complex) ob;
            return m_Re==c.m_Re && m_Im==c.m_Im;
        }
        else {
            return false;
        }
    }

    public override int GetHashCode(){
        return m_Re.GetHashCode() ^ m_Im.GetHashCode();
    }
}
type Complex() =
    member val m_Re = 0. with get, set
    member val m_Im = 0. with get, set

    override this.Equals(ob) =
        match ob with
        | :? Complex as c ->
            this.m_Re = c.m_Re && this.m_Im = c.m_Im
        | _ -> false
        
    override this.GetHashCode() =
        this.m_Re.GetHashCode() ^^^ this.m_Im.GetHashCode()
Public Structure Complex
   Private m_Re As Double
   Private m_Im As Double
       
   Public Overloads Function Equals(ob As Object) As Boolean
      If TypeOf ob Is Complex Then
         Dim c As Complex = CType(ob, Complex)
         Return m_Re = c.m_Re And m_Im = c.m_Im
      Else
         Return False
      End If
   End Function
   
   
   Public Overloads Function GetHashCode() As Integer
      Return m_Re.GetHashCode() ^ m_Im.GetHashCode()
   End Function

End Structure

注解

方法 GetHashCode 适用于派生自 ValueType的类型。 派生类型的一个或多个字段用于计算返回值。 如果调用派生类型的 GetHashCode 方法,则返回值不太可能适合用作哈希表中的键。 此外,如果其中一个或多个字段的值发生更改,则返回值可能变得不适合用作哈希表中的键。 在任一情况下,请考虑编写方法的 GetHashCode 自己的实现,以更接近地表示类型的哈希代码的概念。

有关详细信息,请参阅 Object.GetHashCodeSystem.Collections.Hashtable

Windows 运行时说明

对 Windows 运行时 结构调用 GetHashCode 方法时,它为不重写 GetHashCode的值类型提供默认行为。 这是 .NET 为 Windows 运行时 (请参阅 Windows 应用商店应用的 .NET 支持和Windows 运行时) 提供的支持的一部分。 Windows 运行时结构不能重写 GetHashCode,即使它们使用 C# 或 Visual Basic 编写,因为它们不能有方法。 (此外,Windows 运行时中的结构本身不会继承 ValueType.) 但是,当你在 C# 或 Visual Basic 代码中使用时,它们似乎具有 ToStringEqualsGetHashCode 方法,并且 .NET 为这些方法提供默认行为。

适用于