[英]C# Equality for classes having array properties
我有以下價值
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, ProjectId = 42 }
實際:標識 { FileContent = [56, 192, 243], Id = 8, ProjectId = 42 }
如果重要的話,我將 Npgsql 與 Dapper 一起使用。
您應該將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
可能很耗時,我已經將它移到比較的末尾(如果ProjectId
不相等,則無需檢查數組)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.