2011-02-16 103 views
1

我有一個類似類型的多個屬性的檢查:動態平等類型的對象

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)); 
} 

但我想以這樣的方式來實現這個方法,它動態地檢查所有的現有屬性(或這種類型的,也許某些屬性)的平等,而不明確地編寫代碼用於比較檢查如上。

希望我能清楚地表達我的問題。 :)

謝謝!

回答

2

您可以編寫一個自定義屬性,該屬性附加到您想要包含在比較中的類型的屬性上。然後在Equals方法中,您可以反映該類型並提取具有該屬性的所有屬性,並動態地對它們進行比較。

的僞代碼:

[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; 
    } 
} 

它會certianly需要比這更復雜一點,但應該希望你設定在正確的軌道:)

+0

恩,謝謝。會試試這個。 – Dienekes 2011-02-16 09:54:17

1

兩個Order s被認爲在上如果它們的所有屬性都相同,則相同這4個屬性名稱/總購買量/金額/代碼是可以的,它們的默認比較器正是你想要的。但對於屬性AllItems(其類型爲List<IItem>),您必須告訴他們認爲他們是如何平等的。目前您使用的引用等於不正確。 this.AllItems.Equals(other.AllItems)應該是這樣的:

this.AllItems.SequenceEqual(other.AllItems, new ItemComparer()) 

而且ItemComparer是一個類實現IEqualityComparer<Item>告訴如何檢查兩個Item s爲相等。

+0

我會說你甚至不想在比較中包含AllItems屬性。唯一需要比較的屬性是讓訂單唯一(名稱代碼?)的屬性。理想情況下它應該有一個唯一的標識符。你的建議是好的,但假設他想要比較列表:) – MattDavey 2011-02-16 09:23:16