C# 具有数组属性的类的相等性

问题描述 投票:0回答:1

我有以下价值

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。

c# arrays equality
1个回答
2
投票

您应该对数组使用

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
未能相等,则无需检查数组)

© www.soinside.com 2019 - 2024. All rights reserved.