2016-09-26 40 views
1

我具有以下值C#平等具有陣列屬性的類

public class Identification : IEquatable<Identification> 
{ 
    public int Id { get; set; } 
    public byte[] FileContent { get; set; } 
    public int ProjectId { get; set; } 
} 

其中我生成平等部件用於與ReSharper的

public bool Equals(Identification other) 
    { 
     if (ReferenceEquals(null, other)) return false; 
     if (ReferenceEquals(this, other)) return true; 
     return Id == other.Id && Equals(FileContent, other.FileContent) && ProjectId == other.ProjectId; 
    } 

    public override bool Equals(object obj) 
    { 
     if (ReferenceEquals(null, obj)) return false; 
     if (ReferenceEquals(this, obj)) return true; 
     if (obj.GetType() != this.GetType()) return false; 
     return Equals((Identification) obj); 
    } 

    public override int GetHashCode() 
    { 
     unchecked 
     { 
      var hashCode = Id; 
      hashCode = (hashCode*397)^(FileContent != null ? FileContent.GetHashCode() : 0); 
      hashCode = (hashCode*397)^ProjectId; 
      return hashCode; 
     } 
    } 

    public static bool operator ==(Identification left, Identification right) 
    { 
     return Equals(left, right); 
    } 

    public static bool operator !=(Identification left, Identification right) 
    { 
     return !Equals(left, right); 
    } 

但是,當欲單元測試之前和從返回後的平等它失敗的存儲庫。儘管在失敗消息中具有完全相同的屬性。

var identification = fixture 
       .Build<Identification>() 
       .With(x => x.ProjectId, projet.Id) 
       .Create(); 
await repository.CreateIdentification(identification); 
var returned = await repository.GetIdentification(identification.Id); 

Assert.Equal()故障

預期:標識{FileContent = [56,192,243],ID = 8,專案編號= 42}

實際:識別{FileContent = [56,192,243],Id = 8,ProjectId = 42}

我在使用Npgsql和Dapper(如果它很重要)。

+5

數組比較是引用相等,只需將其替換爲SequenceEquals() –

回答

1

您應該使用Enumerable.SequenceEqual爲其檢查數組:

  • 兩個陣列都是null或兩個數組都是不null
  • 兩個陣列都有相同的Length
  • 相關項目相等。

像這樣的事情

public bool Equals(Identification other) 
{ 
    if (ReferenceEquals(null, other)) 
     return false; 
    else if (ReferenceEquals(this, other)) 
     return true; 

    return Id == other.Id && 
      ProjectId == other.ProjectId && 
      Enumerable.SequenceEqual(FileContent, other.FileContent); 
} 

由於Enumerable.SequenceEqual能夠很好地時間cosuming我已經轉向到比較結束(有沒有需要檢查陣列如果說,ProjectId如未能按要求等於)