Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. public class Foo
  2. {
  3. public int FooId { get; set; }
  4. public string FooName { get; set; }
  5.  
  6. public override bool Equals(object obj)
  7. {
  8. Foo fooItem = obj as Foo;
  9.  
  10. return fooItem.FooId == this.FooId;
  11. }
  12.  
  13. public override int GetHashCode()
  14. {
  15. // Which is preferred?
  16. return base.GetHashCode();
  17. //return this.FooId.GetHashCode();
  18. }
  19. }
  20.  
  21. unchecked //Solo es necesario si está compilando con los controles aritméticos
  22. {//Por defecto están deshabilitados, así la mayoría de la gente no lo necesitará.
  23. int hash = 13;
  24. hash = (hash * 7) + field1.GetHashCode();
  25. hash = (hash * 7) + field2.GetHashCode();
  26. ...
  27. return hash;
  28. }
  29.  
  30. public class Gato
  31. {
  32. public string Nombre {get; set;}
  33. public string Raza {get; set;}
  34. public string NombrePoseedor {get; set;}
  35. }
  36. //dos instancias mismas propiedades
  37.  
  38. var GatoUno= new Gato{Nombre="asrael",Raza="comun", NombrePoseedor="Gargamel"};
  39.  
  40. var GatoDos= new Gato{Nombre="asrael",Raza="comun" ,NombrePoseedor="Gargamel"};
  41.  
  42. //declarando una comparacion
  43. Console.WriteLine($"Gatos Iguales? = { GatoUno.Equals(GatoDos) }");
  44. //Gatos Iguales? = false
  45.  
  46. var gatosDictionary = new Dictionary<Gatos, int> { { GatoUno, 1 } };
  47. var salida= gatosDictionary.ContainsKey(GatoDos) ;
  48.  
  49.  
  50. Console.WriteLine($"Ya existe? {salida}");
  51. //false
  52. Console.WriteLine(GatoUno.GetHashCode()); // 3423423
  53. Console.WriteLine(GatoDos.GetHashCode()); // 465464
  54.  
  55. public override int GetHashCode() =>
  56. new { Nombre, NombrePoseedor }.GetHashCode();
  57.  
  58. var salida= gatosDictionary.ContainsKey(GatoDos) ;
  59. //salida= true
  60. Espero haya quedado claro la rapida explicacion,
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement