Advertisement
Guest User

Untitled

a guest
Jan 17th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4.  
  5. public abstract class ValueObject<T> : IEquatable<T>
  6. where T : ValueObject<T>
  7. {
  8. public override bool Equals(object obj)
  9. {
  10. if (obj == null)
  11. return false;
  12.  
  13. T other = obj as T;
  14.  
  15. return Equals(other);
  16. }
  17.  
  18. public override int GetHashCode()
  19. {
  20. IEnumerable<FieldInfo> fields = GetFields();
  21.  
  22. int startValue = 17;
  23. int multiplier = 59;
  24.  
  25. int hashCode = startValue;
  26.  
  27. foreach (FieldInfo field in fields)
  28. {
  29. object value = field.GetValue(this);
  30.  
  31. if (value != null)
  32. hashCode = hashCode * multiplier + value.GetHashCode();
  33. }
  34.  
  35. return hashCode;
  36. }
  37.  
  38. public virtual bool Equals(T other)
  39. {
  40. if (other == null)
  41. return false;
  42.  
  43. Type t = GetType();
  44. Type otherType = other.GetType();
  45.  
  46. if (t != otherType)
  47. return false;
  48.  
  49. FieldInfo[] fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  50.  
  51. foreach (FieldInfo field in fields)
  52. {
  53. object value1 = field.GetValue(other);
  54. object value2 = field.GetValue(this);
  55.  
  56. if (value1 == null)
  57. {
  58. if (value2 != null)
  59. return false;
  60. }
  61. else if (!value1.Equals(value2))
  62. return false;
  63. }
  64.  
  65. return true;
  66. }
  67.  
  68. private IEnumerable<FieldInfo> GetFields()
  69. {
  70. Type t = GetType();
  71.  
  72. List<FieldInfo> fields = new List<FieldInfo>();
  73.  
  74. while (t != typeof(object))
  75. {
  76. fields.AddRange(t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));
  77.  
  78. t = t.BaseType;
  79. }
  80.  
  81. return fields;
  82. }
  83.  
  84. public static bool operator ==(ValueObject<T> x, ValueObject<T> y)
  85. {
  86. return x.Equals(y);
  87. }
  88.  
  89. public static bool operator !=(ValueObject<T> x, ValueObject<T> y)
  90. {
  91. return !(x == y);
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement