.NET XmlIgnore 默认情况下? [英] .NET XmlIgnore By Default?
问题描述
有没有办法让 XmlSerializer 默认忽略所有成员,除非我另有说明?
Is there a way to have XmlSerializer ignore all members by default, unless I say otherwise?
我有一个基类和几个派生类,有很多成员,但大多数我不想被序列化.序列化只能接受少数几个.
I have a base class and several derived classes with lots of members, but most I do not want to be serialized. Only a select few are acceptable for serialization.
推荐答案
不,您不能这样做.
XmlSerializer 正在使用选择退出"过程 - 它将序列化所有内容(所有公共属性),除非您使用 [XmlIgnore]
属性明确选择退出.没有办法改变这种行为.
The XmlSerializer is using a "opt-out" process - it will serialize everything (all public properties) unless you explicitly opt-out by using the [XmlIgnore]
attribute. There's no way of changing this behavior.
另一方面,.NET 3.5 DataContractSerializer 采用另一种方法 - 选择加入.它不会序列化任何东西,除非你特别告诉它,通过用 [DataMember]
装饰你的成员.
The .NET 3.5 DataContractSerializer on the other hand is taking the other approach - opt-in. It will not serialize anything, unless you specifically tell it to, by decorating your members with [DataMember]
.
那么也许 DataContract 序列化程序适合您?它还有一些优点(不需要无参数构造函数,也可以序列化内部和私有属性,如果需要,它还可以序列化字段而不是属性),并且它已针对速度进行了调整.也有一些缺点 - 它不支持 XML 节点中的属性 - 因此您必须根据您的要求进行选择.
So maybe the DataContract serializer would work for you? It was a few more advantages (doesn't require a parameter-less constructor, can serialize internal and private properties, too, and it can also serialize fields instead of properties, if needed), and it's tuned for speed. There's some downsides, too - it doesn't support attributes in XML nodes - so you'll have to pick based on your requirements.
Dan Rigsby - 看看吧!
马克
这篇关于.NET XmlIgnore 默认情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!