PropertyComparer.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. namespace ShwasherSys
  8. {
  9. public class PropertyComparer<T> : IEqualityComparer<T>
  10. {
  11. private PropertyInfo _PropertyInfo;
  12. /// <summary>
  13. /// 通过propertyName 获取PropertyInfo对象 /// </summary>
  14. /// <param name="propertyName"></param>
  15. public PropertyComparer(string propertyName)
  16. {
  17. _PropertyInfo = typeof(T).GetProperty(propertyName,
  18. BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
  19. if (_PropertyInfo == null)
  20. {
  21. throw new ArgumentException($"{propertyName} is not a property of type {typeof(T)}.");
  22. }
  23. }
  24. #region IEqualityComparer<T> Members
  25. public bool Equals(T x, T y)
  26. {
  27. object xValue = _PropertyInfo.GetValue(x, null);
  28. object yValue = _PropertyInfo.GetValue(y, null);
  29. if (xValue == null)
  30. return yValue == null;
  31. return xValue.Equals(yValue);
  32. }
  33. public int GetHashCode(T obj)
  34. {
  35. object propertyValue = _PropertyInfo.GetValue(obj, null);
  36. if (propertyValue == null)
  37. return 0;
  38. else
  39. return propertyValue.GetHashCode();
  40. }
  41. #endregion
  42. }
  43. }