You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CompareNetObjects NuGet包获取同类型复杂对象的新值?

使用CompareNetObjects提取对象差异并生成仅含新值的对象

要从ComparisonResult.Differences生成包含新值的MyType对象,你可以通过反射解析差异项的属性路径,将每个差异的新值映射到新创建的MyType实例中。以下是具体实现:

基础实现(支持嵌套属性)

CompareLogic compareLogic = new CompareLogic();
compareLogic.Config.MaxDifferences = int.MaxValue;
compareLogic.Config.ShowBreadcrumb = false;

MyType originalData;
MyType newData;

ComparisonResult myComparison = compareLogic.Compare(originalData, newData);
var differences = myComparison.Differences;

// 创建空的目标对象
MyType changedData = new MyType();

foreach (var diff in differences)
{
    string propertyPath = diff.PropertyName;
    object newValue = diff.Object2; // 新数据中的值
    var target = changedData;
    string[] pathSegments = propertyPath.Split('.');

    for (int i = 0; i < pathSegments.Length; i++)
    {
        string segment = pathSegments[i];
        PropertyInfo prop = target.GetType().GetProperty(segment);
        if (prop == null) continue; // 忽略不存在的属性(可选)

        if (i == pathSegments.Length - 1)
        {
            // 最后一段是目标属性,直接赋值
            prop.SetValue(target, newValue);
        }
        else
        {
            // 嵌套对象,若为空则创建实例
            object nestedObj = prop.GetValue(target);
            if (nestedObj == null)
            {
                nestedObj = Activator.CreateInstance(prop.PropertyType);
                prop.SetValue(target, nestedObj);
            }
            target = nestedObj;
        }
    }
}

关键说明

  • 这段代码会遍历所有差异项,根据PropertyName解析属性路径(支持NestedObj.Property这类嵌套格式),在新对象中创建必要的嵌套实例,并将新值赋值到对应属性。
  • 最终的changedData仅包含有变化的属性值,未变化的属性保持MyType的默认值(如null、0等)。
  • 如果你的对象包含集合类型(如List<T>),CompareNetObjects会生成类似List[0].Property的属性路径,此时需要额外解析索引并处理集合元素的赋值,可根据实际需求扩展逻辑。

内容的提问来源于stack exchange,提问作者MrTouya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:01:02