假设你有一个简单的对象如下:
public class PaymentLineItem
{
public DateTime TimeStamp { get; set; }
public decimal Amount { get; set; }
public string Description { get; set; }
public PayCodeDto PayCode { get; set; } //= PayCodeDto.Invalid;
public override string ToString()
{
return StringUtils.ToString(this);
}
public override bool Equals(object obj)
{
return Equals(obj as PaymentLineItem);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = TimeStamp.GetHashCode();
hashCode = (hashCode * 397) ^ Amount.GetHashCode();
hashCode = (hashCode * 397) ^ (Description != null ? Description.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (PayCode != null ? PayCode.GetHashCode() : 0);
return hashCode;
}
}
public bool Equals(PaymentLineItem other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return TimeStamp.Equals(other.TimeStamp)
&& Amount.Equals(other.Amount)
&& string.Equals(Description, other.Description)
&& Object.Equals(PayCode, other.PayCode);
}
}
除了使用C#6.0中引入的新C#auto-property initialize之外,这个类没有什么特别之处。 PayCodeDto 很简单,有三个属性并实现了IEquatable。
如果您创建这些付款项目的集合并使用
序列化 var serialized = JsonConvert.SerializeObject(sut);
然后使用正确的序列化字符串并使用
反序列化 var deserialized = JsonConvert.DeserializeObject<List<PaymentLineItemLight>>(serialized);
您最终得到的是具有相同PayCode的所有订单项实例的集合。
这是样本测试:
[Test]
public void Should_Serialize_Collection_In_Package_Correctly()
{
var sut = new List<PaymentLineItemLight>
{
new PaymentLineItemLight
{
Amount = new decimal(153.0000),
Description = "48385 - Multiple items payment",
TimeStamp = DateTime.Parse("2018-01-30T10:40:47.477"),
PayCode = new PayCodeDto("105", "dont-care") {DictionaryId = 2}
},
new PaymentLineItemLight
{
Amount = new decimal(53.0000),
Description = "483816 - Multiple items payment",
TimeStamp = DateTime.Parse("2018-01-30T10:40:47.477"),
PayCode = new PayCodeDto("104", "dont-care") {DictionaryId = 2}
},
new PaymentLineItemLight
{
Amount = new decimal(200.0000),
Description = "483817 - Multiple items payment",
TimeStamp = DateTime.Parse("2018-01-30T10:40:47.477"),
PayCode = new PayCodeDto("102", "dont-care-102") {DictionaryId = 2}
}
};
var serialized = JsonConvert.SerializeObject(sut);
var deserialized = JsonConvert.DeserializeObject<List<PaymentLineItemLight>>(serialized);
CollectionAssert.AreEqual(sut, deserialized);
}
如果我删除了自动属性初始化,则测试通过。我必须在这里遗漏一些东西。有谁见过这个?