如何使用XmlSerializer的反序列化到现有实例?如何使用、实例、序列化、XmlSerializer

2023-09-04 10:45:29 作者:傲娇派掌门人

是它在某种程度上可以使用的XmlSerializer进行反序列化的数据到一个类的现有实例而不是进入一个新的?

Is it somehow possible to use the XmlSerializer to deserialize its data into an existing instance of a class rather than into a new one?

这将有助于在两种情况下:

This would be helpful in two cases:

在轻松合并两个XML文件合并成一个对象实例。 在让建筑工本身的对象是一个谁是从XML文件中加载数据。

如果无法在默认情况下,应该通过使用反射(复制deserialisation后,每个属性)工作,但,这将是一个丑陋的解决方案。

If the is not possible by default it should work by using reflection (copying each property after the deserialisation) but this would be an ugly solution.

推荐答案

我认为你是在正确的轨道与反思的想法。

I think you're on the right track with the Reflection idea.

因为你可能有各地的XML操作的封装,无论如何,你可能需要在目标对象,执行反序列化正常到一个新的对象,然后做类似的东西克隆复制了一个接一个只持有非的属性默认值。

Since you probably have a wrapper around the XML operations anyway, you could take in the destination object, do the deserialization normally into a new object, then do something similar to cloning by copying over one by one only the properties holding non-default values.

这不应该是复杂的,以实现这一点,它看起来对消费者从应用程序的其他部分一样,就地反序列化。

It shouldn't be that complex to implement this, and it would look to consumers from the rest of your application just like in-place deserialization.