为什么在序列化ObservableCollection< T>?时无法添加属性?

编程入门 行业动态 更新时间:2024-10-15 08:19:50
本文介绍了为什么在序列化ObservableCollection< T>?时无法添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用一些自定义属性扩展ObservableCollection并让它序列化。但是,我似乎无法让它序列化这些属性。我正在使用.NET 4.0,他们修复了ObservableCollection的序列化问题,但仍然遇到问题。我的预感是在基类上调用GetObjectData而不是我的。有什么想法吗?

I'm trying to extend an ObservableCollection with a few custom properties and have it serialize. However, I can't seem to get it to serialize these properties. I'm using .NET 4.0 where they fixed the serialization issues of ObservableCollection, but am still having problems. My hunch is that GetObjectData is being called on the base class and not mine. Any ideas?

[Serializable] [XmlRoot(ElementName = "MyCollection")] public class MyCollection : ObservableCollection<MyItem>, ISerializable { private string name; void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", Name); } private MyCollection() { Name = string.Empty; } public MyCollection(string name) { Name = name; } public MyCollection(SerializationInfo info, StreamingContext context) { Name = (string)info.GetValue("Name", typeof(string)); } [XmlAttribute] public string Name { get { return name; } protected set { string originalName = name; name = value; if (originalName != name) OnPropertyChanged(new PropertyChangedEventArgs("Name")); } } public void SaveToFile(string path) { string directory = Path.GetDirectoryName(path); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); XmlSerializer serializer = new XmlSerializer(typeof(MyCollection)); using (TextWriter textWriter = new StreamWriter(path)) { serializer.Serialize(textWriter, this); textWriter.Close(); } } public static MyCollection LoadFromFile(string path) { XmlSerializer deserializer = new XmlSerializer(typeof(MyCollection)); using (TextReader textReader = new StreamReader(path)) { MyCollection myCollection = (MyCollection)deserializer.Deserialize(textReader); textReader.Close(); return myCollection; } } }

推荐答案

XML序列化不支持此方案。您根本无法向实现 ICollection 的类添加任何内容。

XML Serialization does not support this scenario. You simply cannot add anything to a class implementing ICollection.

如果你需要这个,那么你必须实现 IXmlSerializable 并自己完成工作。

If you require this, then you will have to implement IXmlSerializable and do the work yourself.

请注意,您可能会将XML序列化与运行时序列化混淆。 XML Serialization不关心 [Serializable] 属性或 GetObjectData 等。

Note that you may be confusing XML Serialization with runtime serialization. XML Serialization doesn't care about the [Serializable] attribute or GetObjectData, etc.

更多推荐

为什么在序列化ObservableCollection&lt; T&gt;?时无法添加属性?

本文发布于:2023-11-12 10:50:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581282.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   序列化   ObservableCollection   amp   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!