在 VB.Net 中序列化 ObservableCollection(of T)

发布于 2024-08-07 11:25:27 字数 272 浏览 5 评论 0原文

我正在 VB.Net 中尝试 MVVM 一段时间,并开始使用 List(of T) 的一些实体,我将其通过 xml 序列化到磁盘。现在,我更新了列表使用的类来实现 INotifyPropertyChanged,因此我还将 List(of T) 更改为 ObservableCollection(of T)。

之后,XML 序列化器停止工作:'( 一位同事告诉我,ObservableCollections 与通用列表不同,是不可序列化的。

如果是这样,那么我怎样才能使它们可序列化?提前致谢~!:D

I'm trying out MVVM in VB.Net for a while now and started out with some of my entities using List(of T)s, which I xml serialized to disk. Now, I updated the classes used by the Lists to implement INotifyPropertyChanged so I also changed the List(of T)s to ObservableCollection(of T)s.

After which, the XML serializer stopped working :'( A colleague told me that ObservableCollections, unlike generic Lists, are not serializable.

If so then how can I make them Serializable? Thanks in Advance~! :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阳光下慵懒的猫 2024-08-14 11:25:27

你的大学只说对了一半。 ObservableCollection(Of T) 确实是可序列化的,但它是通过二进制序列化器而不是 XML 序列化器实现的。

您可以采取什么措施来解决此问题,将 ObservableCollection(Of T) 的任何集合的序列化与 List(Of T) 包装在一起。只需在序列化时进行转换即可。

例如 ...

Public Sub Serialize(ByVal col as ObservableCollection(Of Integer))
  Dim list = New List(Of Integer)(col)
  ReallySerialize(list)
End Sub

Public Function Unserialize() As ObserableCollection(Of Integer)
  Dim list = ReallyUnserialize()
  return New ObservableCollection(Of Integer)(list)
End Function

Your college is half correct. ObservableCollection(Of T) is indeed serializable but it is so through the binary serializer, not the XML one.

What you can do to work around this to wrap the serialization of any collections of ObservableCollection(Of T) with List(Of T). Just do the conversion at the point of serialization.

For example ...

Public Sub Serialize(ByVal col as ObservableCollection(Of Integer))
  Dim list = New List(Of Integer)(col)
  ReallySerialize(list)
End Sub

Public Function Unserialize() As ObserableCollection(Of Integer)
  Dim list = ReallyUnserialize()
  return New ObservableCollection(Of Integer)(list)
End Function
遇到 2024-08-14 11:25:27

@JaredPar 的答案仅适用于二进制序列化器,不适用于 Xml 序列化器,XmlSerializer 确实适合我(在 VS2010 中)。

//ObservableCollection<Customer> customers = Code to load customers 

//write to file
   XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
   using (StreamWriter wr = new StreamWriter("myfile.xml")) {
        xs.Serialize(wr, customers);
   }

@JaredPar's answer re only Binary serializer works not the Xml one, the XmlSerializer does work for me (in VS2010).

//ObservableCollection<Customer> customers = Code to load customers 

//write to file
   XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
   using (StreamWriter wr = new StreamWriter("myfile.xml")) {
        xs.Serialize(wr, customers);
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文