【发布时间】:2023-03-04 23:57:01
【问题描述】:
鉴于我有两个相同类型的 c# 对象,我想比较它们以创建 JsonPatchDocument。
我有一个这样定义的 StyleDetail 类:
public class StyleDetail
{
public string Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal OriginalPrice { get; set; }
public decimal Price { get; set; }
public string Notes { get; set; }
public string ImageUrl { get; set; }
public bool Wishlist { get; set; }
public List<string> Attributes { get; set; }
public ColourList Colours { get; set; }
public SizeList Sizes { get; set; }
public ResultPage<Style> Related { get; set; }
public ResultPage<Style> Similar { get; set; }
public List<Promotion> Promotions { get; set; }
public int StoreStock { get; set; }
public StyleDetail()
{
Attributes = new List<string>();
Colours = new ColourList();
Sizes = new SizeList();
Promotions = new List<Promotion>();
}
}
如果我有两个 StyleDetail 对象
StyleDetail styleNew = db.GetStyle(123);
StyleDetail styleOld = db.GetStyle(456);
我现在想创建一个 JsonPatchDocument,以便将差异发送到我的 REST API... 怎么做??
JsonPatchDocument patch = new JsonPatchDocument();
// Now I want to populate patch with the differences between styleNew and styleOld - how?
在javascript中,有一个库可以做到这一点https://www.npmjs.com/package/rfc6902
计算两个对象之间的差异:
rfc6902.createPatch({first: 'Chris'}, {first: 'Chris', last: '棕色'});
[ { op: 'add', path: '/last', value: 'Brown' } ]
但我正在寻找一个 c# 实现
【问题讨论】:
-
我知道这有点老了……但你有没有想过如何做到这一点?我正在寻找完全相同的东西!
-
您可以使用反射来遍历属性并比较它们。有关迭代属性的示例,请参阅此问题:stackoverflow.com/questions/1198886/…
标签: c# json-patch