C# 使用多个列表/集合中的对象序列化数据结构
在 C# 中,我希望序列化一种数据结构,其中对象可以属于多个集合。
例如,我有一个 Person 类。我还有一个 Family 类和 School 类,每个类都包含一个 MemberList。 Person 类的实例可以出现在 Family 和 School 的 MemberList 中。
我希望序列化整个数据结构,但担心 Person 类的实例最终将被存储为两个单独的实例,并且在反序列化时我最终将得到两个实例而不是一个实例。串行器是否足够聪明来存储数据以使这种情况不会发生?如果是的话有什么办法可以阻止这种情况发生吗?
任何帮助或建议表示赞赏。
In C# I wish to serialise a data structure where objects can belong to more than one collection.
For example, I have a Person class. I also have a Family class and School class, which each contain a MemberList. An instance of the Person class can be present in both the MemberList of the Family and the School.
I wish to serialise the entire data structure but am concerned that the instance of the Person class will end up being stored as two separate instances and upon deserialisation I will end up with two instances instead of one. Is the serialiser clever enough to store the data so that this will not happen? Is there any way to stop this happening if so?
Any help or suggestions appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,它将序列化整个对象图 - 因此对象实例将被复制。自定义序列化是唯一的选择,可以手动或通过覆盖对象的默认序列化 - 两者都涉及。
我不会太担心它,除非它成为一个问题。第一遍就可以序列化整个图。
It will serialize the entire object graph, to my knowledge - so object instances will be duplicated. Custom serialization is the only option, either manually or by overriding the default serialization of an object - both are involved.
I wouldn't worry about it too much, not until it becomes an issue anyway. First pass it will be fine to serialize the entire graph.
您可以使用 DataContractSerializer(WCF 使用)并使用 DataContract 属性和设置为 true 的“IsReference”属性来装饰每个类(Family 和 School),如下所示:
这将告诉 DataContractSerializer 在重新创建时保持引用完整反序列化时的对象图。
您可以使用 DataContractSerializer 将对象“objectInstance”序列化为流,如下所示:
请注意,您实际上不必使用 WCF,只需使用 DataContractSerializer 来序列化/反序列化对象图。
您可以在 MSDN 此处阅读有关此属性的更多信息。
另外,这里是一个基本示例使用“IsReference”属性。
You could use the DataContractSerializer (which is used by WCF) and decorate each class (Family and School) with the DataContract attribute and the 'IsReference' property set to true, like so:
This will tell the DataContractSerializer to keep the references intact when recreating the object graph on deserialization.
You can serialize the object 'objectInstance' to a stream with DataContractSerializer like so:
Note that you don't actually have to use WCF, you can just use the DataContractSerializer to serialize/deserialize the object graph.
You can read more about this attribute on MSDN here.
Also, here is a basic example of how to use the 'IsReference' property.