Csharp/C Sharp/Development Class/Hash Code

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Class behaves properly using overridden Equals and GetHashCode methods

using System;
using System.Collections;
public class GoodCompare {
  public static void Main() {
    Name president = new Name ("A", "B");
    Name first = new Name ("C", "D");
    Console.WriteLine("The hash codes for first and president are: ");
    
    if (president.GetHashCode() == first.GetHashCode())
       Console.WriteLine("equal");
    else
       Console.WriteLine("not equal");
    
  }
}

public class Name {
  protected String first;
  protected char initial;
  protected String last;
          
  public Name(String f, String l) {
    first = f; 
    last = l; 
  }
  public Name(String f, char i, String l) : this(f,l) {
    initial = i;  
  } 
  public override String ToString() {
    if (initial == "\u0000")
       return first + " " + last;
    else  
       return first + " " + initial + " " + last;
  }
  public override bool Equals(Object o) {
    if (!(o is Name))
       return false;
    Name name = (Name)o;
    return first == name.first && initial == name.initial
             && last == name.last;
  }
  public override int GetHashCode() {
    return first.GetHashCode() + (int)initial 
                             + last.GetHashCode();
  }
}


Get the Hash code for string value

using System;
public class HashValues {
  public static void Main( ) {    
    String[] identifiers ={"A","B","C","D","E","F","G","H","I","J","K","L"}; 
    
    for(int i = 0; i < identifiers.Length; i++) {
      String id = identifiers[i];
      int hash = id.GetHashCode();
      int code = hash % 23;
      Console.WriteLine("{0,-12}{1,12}{2,12}", id, hash, code);
    }
  }
}