在 C# 中控制序列化的顺序 [英] Controlling order of serialization in C#

查看:42
本文介绍了在 C# 中控制序列化的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 XmlSerializer 来序列化对象并将其写入文件.我已经取得了相当多的成功,序列化程序在嵌套元素方面做我想做的事情,以及将什么序列化为元素与属性.不幸的是,我遇到了一个问题,我需要一个类的一个成员在另一个之前序列化.在其他地方,首先声明的内容首先被序列化对我有用,但在这种情况下,我并没有取得太大的成功.有没有办法手动控制事物序列化的顺序?

I'm using an XmlSerializer to serialize an object and write it to a file. I've had quite a bit of success with the serializer doing what I want it to do in terms of nesting elements and what is serialized as elements vs attributes. Unfortunately, I've run into a problem where I need one member of a class to serialize before another. Elsewhere it's worked for me that whatever is declared first gets serialized first, but in this instance I'm not having so much success with that. Is there any way to manually control the order in which things are serialized?

推荐答案

[XmlElementAttribute(Order = 1)] 
public int Field1 {...} 

[XmlElementAttribute(Order = 2)] 
public int Field2 {...} 

Catch:您必须为所有成员指定Order.

Catch: You must specify the Order for all of your members.

小心 - 只有当 XML 文档中的属性处于相同的顺序时,反序列化才会起作用.否则它会默默地忽略乱序属性.

Be careful - deserialization will only work if the properties in the XML document are in the same order. Otherwise it will silently ignore out-of-order properties.

这篇关于在 C# 中控制序列化的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆