动态等式检查类型对象的多个属性

我有一个类似的类型:
class Order
{
  public List<IItem> AllItems { get; set; }
  public string Name { get; set; }
  public double TotalPurchases { get; set; }
  public long Amount { get; set; }
  public int Code { get; set; }
}
我已经实现了
IEquatable<T>
接口来检查这种类型的两个对象是否相同。目前的
Equals
方法如下:
public virtual bool Equals(Order other)
{
  if ((object)other == null)
  {
    return false;
  }
  return (this.AllItems.Equals(other.AllItems)
       && this.Name.Equals(other.Name)
       && this.TotalPurchases.Equals(other.TotalPurchases)
       && this.Amount.Equals(other.Amount))
       && this.Code.Equals(other.Code));
}
但是我希望以这样的方式实现这个方法,它动态地检查所有现有属性(或者这种类型的某些属性)的相等性,而不显式地为上面的比较检查编写代码。 希望我能够清楚地表达我的问题。 :) 谢谢!     
已邀请:
您可以编写一个自定义属性,该属性附加到您希望包含在比较中的类型属性上。然后在Equals方法中,您可以反映类型并提取具有该属性的所有属性,并动态地对它们进行比较。 Psuedo代码:
[AttributeUsage(AttributeTarget.Property)]
class IncludeInComparisonAttribute : Attribute { }

class Order
{
    List<AllItem> Items { get; set; }

    [IncludeInComparison]
    string Name { get; set; }

    long Amount { get; set; }

    [IncludeInComparison]
    int Code { get; set; }

    override bool Equals(Order other)
    {
        Type orderType = typeof(Order);

        foreach (PropertyInfo property in orderType.GetProperties()
        {
            if (property.CustomAttributes.Includes(typeof(IncludeInComparisonAttribute))
            {
                object value1 = property.GetValue(this);
                object value2 = propetty.GetValue(other);

                if (value1.Equals(value2) == false)
                    return false;
            }
        }

        return true;
    }
}
它确实需要比这更精细,但这应该有希望让你走上正确的轨道:)     
如果它们的所有属性相等,则两个ѭ5被认为是相同的。 4个属性Name / TotalPurchases / Amount / Code是可以的,它们的默认比较器正是你想要的。但对于属性AllItems(其类型为
List<IItem>
),您必须告诉他们如何认为是平等的。目前您正在使用不正确的引用等号。
this.AllItems.Equals(other.AllItems)
应该是这样的:
this.AllItems.SequenceEqual(other.AllItems, new ItemComparer())
并且
ItemComparer
是一个类实现
IEqualityComparer<Item>
来告诉如何检查两个
Item
是否相等。     

要回复问题请先登录注册