Guest User

Untitled

a guest
Jan 20th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ObjectEqualsTest
  9. {
  10. public class Point
  11. {
  12. public Int32 x, y;
  13.  
  14. public Point(int x, int y)
  15. {
  16. this.x = x;
  17. this.y = y;
  18. }
  19.  
  20. public override bool Equals(object obj)
  21. {
  22. if (obj.GetType()!= this.GetType())
  23. return false;
  24.  
  25. FieldInfo[] thisFieldsInfo = this.GetType().GetFields();
  26.  
  27. FieldInfo[] objFieldsInfo = obj.GetType().GetFields();
  28.  
  29. if (thisFieldsInfo.Length != objFieldsInfo.Length)
  30. return false;
  31. else
  32. {
  33. for (int i = 0; i < thisFieldsInfo.Length; i++)
  34. {
  35. if ((thisFieldsInfo[i].GetType() != objFieldsInfo[i].GetType()) &&
  36. (thisFieldsInfo[i].Name != objFieldsInfo[i].Name)&&
  37. (thisFieldsInfo[i].GetValue(this) != objFieldsInfo[i].GetValue(obj)))
  38. {
  39. Console.WriteLine(thisFieldsInfo[i].GetValue(this) + " " + objFieldsInfo[i].GetValue(obj));
  40. return false;
  41. }
  42. else
  43. {
  44. Console.WriteLine(thisFieldsInfo[i].GetValue(this) + " " + objFieldsInfo[i].GetValue(obj));
  45. if (i == thisFieldsInfo.Length - 1)
  46. return true;
  47. }
  48. }
  49. }
  50.  
  51. return false;
  52. }
  53.  
  54. public override int GetHashCode()
  55. {
  56. var hashCode = 1502939027;
  57. hashCode = hashCode * -1521134295 + x.GetHashCode();
  58. hashCode = hashCode * -1521134295 + y.GetHashCode();
  59. return hashCode;
  60. }
  61. }
  62.  
  63.  
  64.  
  65. class Program
  66. {
  67. static void Main(string[] args)
  68. {
  69. Point x1 = new Point(1, 3);
  70. Point x2 = new Point(1, 2);
  71.  
  72. Console.WriteLine(x1.Equals(x2));
  73. Console.ReadKey();
  74. }
  75. }
  76. }
  77.  
  78. if ((thisFieldsInfo[i].GetType() != objFieldsInfo[i].GetType()) &&
  79. (thisFieldsInfo[i].Name != objFieldsInfo[i].Name)&&
  80. (thisFieldsInfo[i].GetValue(this) != objFieldsInfo[i].GetValue(obj)))
Add Comment
Please, Sign In to add comment