2016-05-04 71 views
1

我有實現IEquatable的自定義對象,以便我可以使用List.Contains(anotherCustomObject)。所以如果它包含該對象從列表中刪除它。使用IEquatable失敗的對象比較

問題是我執行的.Equals沒有像預期的那樣工作,只有一些,但現在都顯示爲不相等,並且沒有從列表中刪除。

爲了闡明,在下面的圖片中currentSpecs是我想從中刪除的列表,如果它包含任何來自tmpAS400Specs的。

enter image description here

下面是代碼。

var tmpSpecs = new AS400SpecificationAttribute 
{ 
    ProductNumber = workTask.WIITEM, 
    AttributeGroup = attrGroup, 
    AttributeName = attrName, 
    AttributeValue = attrValue 
}; 

if (currentSpecs.Contains(tmpSpecs)) 
{ 
    currentSpecs.Remove(tmpSpecs); 
} 

代碼比較

public class AS400SpecificationAttribute : IEquatable<AS400SpecificationAttribute> 
{ 
    private string name; 
    private string value; 
    private string group; 
    private string productNumber; 


    public string ProductNumber 
    { 
     get { return productNumber; } 
     set 
     { 
      if (!String.IsNullOrEmpty(value) && !String.IsNullOrWhiteSpace(value)) 
       productNumber = value.Trim().ToUpper(); 
     } 
    } 

    public string AttributeName 
    { 
     get 
     { 
      return this.name; 
     } 
     set 
     { 
      if (!String.IsNullOrEmpty(value) && !String.IsNullOrWhiteSpace(value)) 
       this.name = value.Trim(); 
     } 
    } 
    public string AttributeValue 
    { 
     get 
     { 
      return this.value; 
     } 
     set 
     { 
      if (!String.IsNullOrEmpty(value) && !String.IsNullOrWhiteSpace(value)) 
       this.value = value.Trim().Replace("\\\"","\""); 
     } 
    } 
    public string AttributeGroup 
    { 
     get 
     { 
      return this.group; 
     } 
     set 
     { 
      if (!String.IsNullOrEmpty(value) && !String.IsNullOrWhiteSpace(value)) 
       this.group = value.Trim(); 
     } 
    } 

    public bool Equals(AS400SpecificationAttribute other) 
    { 
     if (other == null) 
      return false; 
     return this.ProductNumber.Equals(other.productNumber) 
      && ((this.group != null && this.group.Equals(other.AttributeGroup)) 
      || (this.group == null && other.AttributeGroup == null)) 
      && ((this.name!= null && this.name.Equals(other.AttributeName)) 
      || (this.name == null && other.AttributeName == null)) 
      && ((this.value != null && this.value.Equals(other.AttributeValue)) 
      || (this.value == null && other.AttributeName == null)); 
    } 
} 

爲什麼比較無法檢測,這兩個屬性是一樣的嗎?

+0

似乎你錯過了一些括號,內部括號有點像這樣:'((a && b)|| c && d)'c && d'不應該在括號內? '((this.group!= null && this.group.Equals(other.AttributeGroup))|| this.group == null && other.AttributeGroup == null)' –

+0

您可以向我們展示完整的類至少是屬性實現嗎? –

+0

@ LasseV.Karlsen真正固定但不是主要問題,仍然遇到錯誤。 –

回答

1

我注意到了這一點:

Object A.value = 'x', Object B.value = 'X'.

儘量使其不區分大小寫,或者確保你的對象是真正的平等。

0
public override bool Equals(object obj) 
{ 
    var other = obj as AS400SpecificationAttribute; 
    if (other == null) 

...等

+0

'List '使用'IEquatable ',因爲它使用'EqualityComparer .Default',因此它被實現。 –

+0

我認爲這將是很好的闡述這個答案。 – Kamo