如诗
如诗
发布于 2025-11-12 / 9 阅读
0
0

cshap实现两个对象的合并

在一些情况下,我们并不清楚匿名对象具备哪些属性,当需要合并两个匿名对象时,手动实现比较复杂,可以直接使用TypeMerger来实现merge

TypeMerger简单使用

TypeMerger是 .NET Core中的对象合并方法,支持多种合并处理方式,这里只简单的使用一下。

var config1 = new {
	name = "Tom",
	age = 18
};

var config2 = new {
    age = 20,
	desc = "A student in high school",
	experience = new
	{
		first = "Grade 6 of primary school won the third prize in football",
		second = "I was the first in my class in the final exam of the third year of junior high school"
	}
}

返回结果:

{
  "name": "Tom",
  "age": 18,
  "desc": "A student in high school",
  "experience": {
    "first": "Grade 6 of primary school won the third prize in football",
    "second": "I was the first in my class in the final exam of the third year of junior high school"
  }
}

直接merge两个对象(JObject或者匿名对象),如果两个对象有相同属性,默认情况下,第二个对象的属性值会被忽略。

如果想要第二个对象的age,代码微调:

var mergeConfig = TypeMerger.TypeMerger.Ignore(() => config1.age).Merge(config1, config2);
var configString = JsonConvert.SerializeObject(mergeConfig);
Console.WriteLine(configString);

或者调整object的顺序即可。


评论