C# 比较两个忽略顺序的对象列表
即使两个列表包含相同的对象,使用MSTest V2和C# 比较两个忽略顺序的对象列表,c#,mstest,C#,Mstest,即使两个列表包含相同的对象,使用MSTest V2和CollectionAssert.AreEquivalent()也会失败: // User-defined object public class ClientDto { public string FullName { get; set; } public decimal RentShare { get; set; } } // Test method var expectedShares = new List<C
CollectionAssert.AreEquivalent()
也会失败:
// User-defined object
public class ClientDto
{
public string FullName { get; set; }
public decimal RentShare { get; set; }
}
// Test method
var expectedShares = new List<ClientDto>
{
new ClientDto
{
FullName = "Harry Potter",
RentShare = 500m
},
new ClientDto
{
FullName = "Ron Weasley",
RentShare = 300m
},
};
var actualShares = new List<ClientDto>
{
new ClientDto
{
FullName = "Ron Weasley",
RentShare = 300m
},
new ClientDto
{
FullName = "Harry Potter",
RentShare = 500m
},
};
CollectionAssert.AreEquivalent(expectedShares, actualShares);
//用户定义的对象
公共类客户端
{
公共字符串全名{get;set;}
公共十进制出租共享{get;set;}
}
//试验方法
var expectedShares=新列表
{
新客户
{
全名=“哈利波特”,
租金份额=5亿
},
新客户
{
FullName=“Ron Weasley”,
租金份额=3亿
},
};
var actualShares=新列表
{
新客户
{
FullName=“Ron Weasley”,
租金份额=3亿
},
新客户
{
全名=“哈利波特”,
租金份额=5亿
},
};
收款资产相当于(预期股份、实际股份);
由于类
ClientDto
未实现IEquatable
或IEquatable
,实例使用引用等式进行比较,因此在ClientDto
中是否还有其他需要实现的内容
因此,列表中的实例将无法进行比较,即使它们包含相同的数据,因为它们的引用不同
要解决此问题,只需实现IEquatable
,以便CollectionAssert.AreEquivalent()
可以正确比较对象:
public class ClientDto: IEquatable<ClientDto>
{
public string FullName { get; set; }
public decimal RentShare { get; set; }
public bool Equals(ClientDto? other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return FullName == other.FullName && RentShare == other.RentShare;
}
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((ClientDto) obj);
}
public override int GetHashCode()
{
unchecked
{
return (FullName.GetHashCode() * 397) ^ RentShare.GetHashCode();
}
}
public static bool operator ==(ClientDto? left, ClientDto? right)
{
return Equals(left, right);
}
public static bool operator !=(ClientDto? left, ClientDto? right)
{
return !Equals(left, right);
}
}
尝试按照本例中所示的方式实现,然后使用。谢谢,但我想知道
CollectionAssert.AreEquivalent()
的答案。谢谢Matt,我刚刚将ClientDto中的代码插入到了中,效果很好。因此,要么我购买ReSharper,要么升级到C#9(我认为目前是C#7或C#8)。我不太理解ReSharper生成的代码,但必须阅读IEquatable
的全部内容。@silver如果您使用的是Visual Studio 2019,它可以自动为您生成IEquatable
实现,与ReSharper的操作非常类似。Saviour!将来一定会查看记录
类型。现在,这正好满足了我的需要。
public record ClientDto
{
public string FullName { get; set; }
public decimal RentShare { get; set; }
}