DataContractSerializer:如何在没有DataContract / DataMember属性的情况下序列化类/成员

编程入门 行业动态 更新时间:2024-10-26 23:27:47
本文介绍了DataContractSerializer:如何在没有DataContract / DataMember属性的情况下序列化类/成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

DataContractSerializer 要求类和成员用 DataContract 和 DataMember 属性。但是,在我的情况下,这些类是使用EFPocoAdapater框架自动生成的,并且这些属性不存在。

DataContractSerializer requires classes and members to be marked with the DataContract and DataMember attributes. However, in my case the classes are auto-generated with the EFPocoAdapater framework and these attributes are not present.

如果没有这些,如何使用DataContractSerializer强制所有成员进行序列化

How can I force serialization of all members using the DataContractSerializer without these attributes being present?

来自Alexdej:

From Alexdej:

此属性在3.5SP1中已更改,希望您看到: www.pluralsight/community/blogs/aaron/archive/2008/05/13/50934.aspx

This changed in 3.5SP1, hope you saw that: www.pluralsight/community/blogs/aaron/archive/2008/05/13/50934.aspx

推荐答案

您不能-简单明了。 DataContractSerializer需要该属性来拾取要序列化的元素。与XmlSerializer的合同(基本上只是对所有内容进行序列化(除非您明确告诉它忽略它))一样,DataContractSerializer是选择加入的-您必须(通过属性)明确告诉它哪些字段和/或属性

You cannot - plain and simple. The attribute are needed for the DataContractSerializer to pick up which elements to serialize. In contract to the XmlSerializer, which basically just serializes everything (unless you explicitly tell it to ignore it), the DataContractSerializer is "opt-in" - you have to explicitly tell it (by means of the attributes) which fields and/or properties to serialize.

更新:正如一些人指出的那样,在.NET 3.5 SP1中,Microsoft放宽了这些规则-任何公众读/写属性将由DataContractSerializer自动序列化。同时,您的类还需要有一个无参数的默认构造函数-听起来像我们对XmlSerializer的确切要求,当......时。

UPDATE: As several folks have pointed out, with .NET 3.5 SP1, Microsoft loosened those rules up a bit - any public read/write property will be serialized automatically by the DataContractSerializer. At the same time, your class also needs to have a parameterless default constructor - sounds like the exact requirements we had for XmlSerializer way back when....

当然,

  • 不允许您序列化某些私有内容-如果要序列化,则必须将其公开公开/写入属性
  • 不允许您指定参数的定义的选定顺序-它将按照它们在类中出现的顺序使用它们
  • 现在要求您再次在类中使用非参数构造函数进行反序列化

我仍然认为这些内容应该是明确的,使不再需要的内容成为懒惰/草率编程的途径-我不喜欢它。但是,如果需要,您可以立即使用它,而无需使用[DataMember]显式标记属性。..

I still think these thing ought to be explicit and clear, making those no longer required opens up the path for lazy/sloppy programming - I don't like it. But if you want to, you can use it now without explicitly marking your properties with [DataMember].....

Marc

更多推荐

DataContractSerializer:如何在没有DataContract / DataMember属性的情况下序列化类/成员

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

发布评论

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

>www.elefans.com

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