DataContractSerializer:如何在没有DataContract / DataMember属性的情况下序列化类/成员 [英] DataContractSerializer: How to serialize classes/members without DataContract/DataMember attributes

查看:92
本文介绍了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中已更改,希望您看到

http://www.pluralsight.com/community/blogs/aaron/archive/2008/05/13/50934.aspx

This changed in 3.5SP1, hope you saw that: http://www.pluralsight.com/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属性的情况下序列化类/成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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