Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
MSDN
MSDN Library
System
 GetHashCode (Método)
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
Object..::.GetHashCode Method

Serves as a hash function for a particular type.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
Public Overridable Function GetHashCode As Integer
C#
public virtual int GetHashCode()
Visual C++
public:
virtual int GetHashCode()
F#
abstract GetHashCode : unit -> int 
override GetHashCode : unit -> int 

Return Value

Type: System..::.Int32
A hash code for the current Object.

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection.

The GetHashCode method is suitable for use in hashing algorithms and data structures such as a hash table.

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

The GetHashCode method can be overridden by a derived type. Value types must override this method to provide a hash function that is appropriate for that type and to provide a useful distribution in a hash table. For uniqueness, the hash code must be based on the value of an instance field or property instead of a static field or property.

Objects used as a key in a Hashtable object must also override the GetHashCode method because those objects must generate their own hash code. If an object used as a key does not provide a useful implementation of GetHashCode, you can specify a hash code provider when the Hashtable object is constructed. Prior to the .NET Framework version 2.0, the hash code provider was based on the System.Collections..::.IHashCodeProvider interface. Starting with version 2.0, the hash code provider is based on the System.Collections..::.IEqualityComparer interface.

Notes to Implementers

A hash function is used to quickly generate a number (hash code) that corresponds to the value of an object. Hash functions are usually specific to each Type and, for uniqueness, must use at least one of the instance fields as input.

A hash function must have the following properties:

  • If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

  • The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.

  • For the best performance, a hash function must generate a random distribution for all input.

For example, the implementation of the GetHashCode method provided by the String class returns identical hash codes for identical string values. Therefore, two String objects return the same hash code if they represent the same string value. Also, the method uses all the characters in the string to generate reasonably randomly distributed output, even when the input is clustered in certain ranges (for example, many users might have strings that contain only the lower 128 ASCII characters, even though a string can contain any of the 65,535 Unicode characters).

For derived classes of Object, the GetHashCode method can delegate to the Object..::.GetHashCode implementation, if and only if that derived class defines value equality to be reference equality and the type is not a value type.

Providing a good hash function on a class can significantly affect the performance of adding those objects to a hash table. In a hash table with a good implementation of a hash function, searching for an element takes constant time (for example, an O(1) operation). In a hash table with a poor implementation of a hash function, the performance of a search depends on the number of items in the hash table (for example, an O(n) operation, where n is the number of items in the hash table). Hash functions must also be inexpensive to compute.

Implementations of the GetHashCode method must not result in circular references. For example, if ClassA.GetHashCode calls ClassB.GetHashCode, ClassB.GetHashCode must not call ClassA.GetHashCode either directly or indirectly.

Implementations of the GetHashCode method must not throw exceptions.

Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly.

In some cases, the GetHashCode method is implemented to simply return an integer value. The following code example illustrates an implementation of GetHashCode that returns an integer value.

There are other more complicated ways to combine hash codes that may give better performance for hash tables.

Visual Basic
Imports System

Public Structure Int32
    Public value As Integer

    'other methods...
    Public Overrides Function GetHashCode() As Integer 
        Return value
    End Function 'GetHashCode
End Structure 'Int32

C#
using System;

public struct Int32 {
   public int value;

   //other methods...

   public override int GetHashCode() {
      return value;
   }
}
Visual C++
using namespace System;
public value struct Int32
{
public:
   int value;

   //other methods...
   virtual int GetHashCode() override
   {
      return value;
   }

};

Frequently, a type has multiple data fields that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an XOR (eXclusive OR) operation, as shown in the following code example.

Visual Basic
Imports System

Public Structure Point
    Public x As Integer
    Public y As Integer

    'other methods
    Public Overrides Function GetHashCode() As Integer 
        Return x Xor y
    End Function 
End Structure 
C#
using System;

public struct Point {
   public int x;
   public int y; 

   //other methods

   public override int GetHashCode() {
      return x ^ y;
   }
}
Visual C++
using namespace System;
public value struct Point
{
public:
   int x;
   int y;

   //other methods
   virtual int GetHashCode() override
   {
      return x ^ y;
   }

};

The following code example illustrates another case where the type's fields are combined using XOR (eXclusive OR) to generate the hash code. Notice that in this code example, the fields represent user-defined types, each of which implements GetHashCode and Equals.

Visual Basic
Imports System

Public Class SomeType
    Public Overrides Function GetHashCode() As Integer 
        Return 0
    End Function 
End Class 

Public Class AnotherType
    Public Overrides Function GetHashCode() As Integer 
        Return 1
    End Function 
End Class 

Public Class LastType
    Public Overrides Function GetHashCode() As Integer 
        Return 2
    End Function 
End Class 

Public Class Demo
    Private a As New SomeType()
    Private b As New AnotherType()
    Private c As New LastType()

    Public Overrides Function GetHashCode() As Integer 
        Return a.GetHashCode() Xor b.GetHashCode() Xor c.GetHashCode()
    End Function 
End Class 
C#
using System;

public class SomeType {
   public override int GetHashCode() {
     return 0;
   }
}

public class AnotherType {
   public override int GetHashCode() {
     return 1;
   }
}

public class LastType {
   public override int GetHashCode() {
     return 2;
   }
}

public class MyClass {
   SomeType a = new SomeType();
   AnotherType b = new AnotherType();
   LastType c = new LastType();

   public override int GetHashCode () {
     return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
   }
}
Visual C++
using namespace System;
public ref class SomeType
{
public:
   virtual int GetHashCode() override
   {
      return 0;
   }

};

public ref class AnotherType
{
public:
   virtual int GetHashCode() override
   {
      return 1;
   }

};

public ref class LastType
{
public:
   virtual int GetHashCode() override
   {
      return 2;
   }

};

public ref class MyClass
{
private:
   SomeType^ a;
   AnotherType^ b;
   LastType^ c;

public:
   virtual int GetHashCode() override
   {
      return a->GetHashCode() ^ b->GetHashCode() ^ c->GetHashCode();
   }

};

If the data member of the derived class is bigger than an Int32, you can combine the high order bits of the value with the low order bits using an XOR (eXclusive OR) operation, as shown in the following code example.

Visual Basic
Imports System

Public Structure Int64
    Public value As Long

    'other methods...
    Public Overrides Function GetHashCode() As Integer 
        Return (Fix(value) Xor Fix(value >> 32))
    End Function 
End Structure 
C#
using System;

public struct Int64 {
   public long value;

   //other methods...

   public override int GetHashCode() {
      return ((int)value ^ (int)(value >> 32));
   }
}
Visual C++
using namespace System;
public value struct Int64
{
public:
   long value;

   //other methods...

   virtual int GetHashCode() override
   {
      return ((int)value ^ (int)(value >> 32));
   }
};

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Biblioteca de clases de .NET Framework
Object..::.GetHashCode (Método)

Actúa como función hash para un tipo concreto.

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)
Visual Basic
Public Overridable Function GetHashCode As Integer
C#
public virtual int GetHashCode()
Visual C++
public:
virtual int GetHashCode()
F#
abstract GetHashCode : unit -> int 
override GetHashCode : unit -> int 

Valor devuelto

Tipo: System..::.Int32
Código hash para la clase Object actual.

Un código hash es un valor numérico que se utiliza para identificar un objeto durante las pruebas de la igualdad. También puede actuar como un índice para un objeto en una colección.

El método GetHashCode es apto para el uso en algoritmos hash y estructuras de datos, como una tabla hash.

La implementación predeterminada del método GetHashCode no garantiza valores devueltos únicos para objetos diferentes. Además, .NET Framework no garantiza la implementación predeterminada del método GetHashCode, y el valor que devuelve será el mismo entre versiones diferentes de .NET Framework. Por consiguiente, la implementación predeterminada de este método no se debe utilizar como identificador de objetos único a efectos de aplicación de algoritmos hash.

El método GetHashCode puede ser reemplazado por un tipo derivado. Los tipos de valor deben reemplazar este método para proporcionar una función hash que sea apropiada para ese tipo y una distribución útil de una tabla hash. Para que los resultados sean únicos, el código hash se debe basar en el valor de una propiedad o campo de instancia, en lugar de en una propiedad o campo estático.

Los objetos utilizados como una clave en un objeto Hashtable también deben reemplazar el método GetHashCode porque esos objetos deben generar su propio código hash. Si un objeto utilizado como una clave no proporciona una implementación útil de GetHashCode, puede especificar un proveedor de código hash al construir el objeto Hashtable. Antes de la versión 2.0 de .NET Framework, el proveedor de código se basaba en la interfaz System.Collections..::.IHashCodeProvider. A partir de la versión 2.0, el proveedor de código hash se basa en la interfaz System.Collections..::.IEqualityComparer.

Notas para los implementadores

Una función hash se utiliza para generar con rapidez un número (código hash) que se corresponda con el valor de un objeto. Las funciones hash suelen ser específicas para cada Type y, para ser únicas, deben utilizar al menos uno de los campos de instancia como entrada.

Una función hash debe tener las siguientes propiedades:

  • Si dos objetos resultan iguales al compararlos, el método GetHashCode para cada objeto debe devolver el mismo valor. Sin embargo, si dos objetos no resultan iguales al compararlos, los métodos GetHashCode para los dos objetos no tienen que devolver valores diferentes.

  • El método GetHashCode para un objeto debe devolver de forma consecuente el mismo código hash mientras no haya ninguna modificación en el estado del objeto que determine el valor devuelto del método Equals del objeto. Observe que esto sólo es cierto para la ejecución actual de una aplicación, y que se puede devolver un código hash diferente si la aplicación se ejecuta de nuevo.

  • Para mejorar el rendimiento, la función hash debe generar una distribución aleatoria para todas las entradas.

Por ejemplo, la implementación del método GetHashCode proporcionada por la clase String devuelve códigos hash idénticos para valores de cadena idénticos. Por ello, dos objetos String devuelven el mismo código hash si representan el mismo valor de cadena. Asimismo, el método utiliza todos los caracteres de la cadena para generar una salida con una distribución aleatoria razonable, incluso en el caso de que la entrada esté agrupada en ciertos intervalos (por ejemplo, es posible que varios usuarios tengan cadenas que contengan únicamente los 128 caracteres ASCII inferiores, aunque una cadena puede contener cualquiera de los 65.535 caracteres Unicode).

En el caso de clases derivadas de Object, el método GetHashCode puede delegar en la implementación de Object..::.GetHashCode única y exclusivamente si dicha clase derivada define la igualdad de valores como igualdad de referencias y el tipo no es un tipo de valor.

El hecho de proporcionar una función hash adecuada a una clase puede influir de forma significativa en el rendimiento a la hora de agregar dichos objetos a una tabla hash. En una tabla hash con una implementación adecuada de una función hash, el tiempo necesario para buscar un elemento es constante (por ejemplo, una operación O(1)). En una tabla hash con una implementación inadecuada de una función hash, el rendimiento de una búsqueda depende del número de elementos de la tabla hash (por ejemplo, una operación O(n), donde n es el número de elementos de la tabla hash). El cálculo de funciones hash no debe llevar mucho tiempo.

Las implementaciones del método GetHashCode no deben dar lugar a referencias circulares. Por ejemplo, si ClassA.GetHashCode llama a ClassB.GetHashCode, ClassB.GetHashCode no debe llamar a ClassA.GetHashCode ni directa ni indirectamente.

Las implementaciones del método GetHashCode no deben producir excepciones.

Las clases derivadas que reemplazan el método GetHashCode también deben reemplazar el método Equals para garantizar que dos objetos considerados iguales tengan el mismo código hash; en caso contrario, puede que el tipo Hashtable no funcione correctamente.

En algunos casos, el método GetHashCode se implementa para devolver simplemente un valor entero. En el ejemplo de código siguiente se muestra una implementación de GetHashCode que devuelve un valor entero.

Hay otras maneras más complicadas de combinar códigos hash que pueden ofrecer mejor rendimiento para las tablas hash.

Visual Basic
Imports System

Public Structure Int32
    Public value As Integer

    'other methods...
    Public Overrides Function GetHashCode() As Integer 
        Return value
    End Function 'GetHashCode
End Structure 'Int32

C#
using System;

public struct Int32 {
   public int value;

   //other methods...

   public override int GetHashCode() {
      return value;
   }
}
Visual C++
using namespace System;
public value struct Int32
{
public:
   int value;

   //other methods...
   virtual int GetHashCode() override
   {
      return value;
   }

};

En ocasiones, un tipo está formado por varios campos de datos que pueden participar en la generación del código hash. Una forma de generar un código hash es combinar estos campos utilizando una operación XOR (eXclusive OR), como se muestra en el siguiente ejemplo de código.

Visual Basic
Imports System

Public Structure Point
    Public x As Integer
    Public y As Integer

    'other methods
    Public Overrides Function GetHashCode() As Integer 
        Return x Xor y
    End Function 
End Structure 
C#
using System;

public struct Point {
   public int x;
   public int y; 

   //other methods

   public override int GetHashCode() {
      return x ^ y;
   }
}
Visual C++
using namespace System;
public value struct Point
{
public:
   int x;
   int y;

   //other methods
   virtual int GetHashCode() override
   {
      return x ^ y;
   }

};

En el siguiente ejemplo de código se muestra otro caso en el que los campos del tipo se combinan utilizando XOR (eXclusive OR) para generar el código hash. Conviene señalar que en este ejemplo de código, los campos representan tipos definidos por el usuario, cada uno de ellos implementa GetHashCode y Equals.

Visual Basic
Imports System

Public Class SomeType
    Public Overrides Function GetHashCode() As Integer 
        Return 0
    End Function 
End Class 

Public Class AnotherType
    Public Overrides Function GetHashCode() As Integer 
        Return 1
    End Function 
End Class 

Public Class LastType
    Public Overrides Function GetHashCode() As Integer 
        Return 2
    End Function 
End Class 

Public Class Demo
    Private a As New SomeType()
    Private b As New AnotherType()
    Private c As New LastType()

    Public Overrides Function GetHashCode() As Integer 
        Return a.GetHashCode() Xor b.GetHashCode() Xor c.GetHashCode()
    End Function 
End Class 
C#
using System;

public class SomeType {
   public override int GetHashCode() {
     return 0;
   }
}

public class AnotherType {
   public override int GetHashCode() {
     return 1;
   }
}

public class LastType {
   public override int GetHashCode() {
     return 2;
   }
}

public class MyClass {
   SomeType a = new SomeType();
   AnotherType b = new AnotherType();
   LastType c = new LastType();

   public override int GetHashCode () {
     return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
   }
}
Visual C++
using namespace System;
public ref class SomeType
{
public:
   virtual int GetHashCode() override
   {
      return 0;
   }

};

public ref class AnotherType
{
public:
   virtual int GetHashCode() override
   {
      return 1;
   }

};

public ref class LastType
{
public:
   virtual int GetHashCode() override
   {
      return 2;
   }

};

public ref class MyClass
{
private:
   SomeType^ a;
   AnotherType^ b;
   LastType^ c;

public:
   virtual int GetHashCode() override
   {
      return a->GetHashCode() ^ b->GetHashCode() ^ c->GetHashCode();
   }

};

Si el miembro de datos de la clase derivada es mayor que Int32, se pueden combinar los bits de orden superior del valor con los bits de orden inferior utilizando una operación XOR (eXclusive OR), tal y como se muestra en el siguiente ejemplo de código.

Visual Basic
Imports System

Public Structure Int64
    Public value As Long

    'other methods...
    Public Overrides Function GetHashCode() As Integer 
        Return (Fix(value) Xor Fix(value >> 32))
    End Function 
End Structure 
C#
using System;

public struct Int64 {
   public long value;

   //other methods...

   public override int GetHashCode() {
      return ((int)value ^ (int)(value >> 32));
   }
}
Visual C++
using namespace System;
public value struct Int64
{
public:
   long value;

   //other methods...

   virtual int GetHashCode() override
   {
      return ((int)value ^ (int)(value >> 32));
   }
};

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker