Why doesn't the XmlSerializer need the type to be marked [Serializable]?

£可爱£侵袭症+ 提交于 2019-11-26 08:24:54

问题


In C#, if I want to serialize an instance with XmlSerializer, the object\'s type doesn\'t have to be marked with [Serializable] attribute. However, for other serialization approaches, such as DataContractSerializer, needs the class be marked as [Serializable] or [DataContract].

Is there any standard or pattern about serialization requirement?


回答1:


This is because XmlSerializer only serializes public fields/properties. Other forms of serialization can serialize private data, which constitutes a potential security risk, so you have to "opt in" using an attribute.




回答2:


Security isn't the only issue; simply, serialization only makes sense for certain classes. For example, it makes little snse to serialize a "connection". A connection string, sure, but the connection itself? nah. Likewise, anything that requires an unmanaged pointer/handle is not going to serialize very well. Nor are delegates.

Additionally, XmlSerializer and DataContractSerializer (by default) are tree serializers, not graph serializers - so any recursive links (like Parent) will cause it to break.

Marking the class with the serializer's preferred token is simply a way of saying "and it should make sense".

IIRC, both [XmlSerializer and [DataContractSerializer] used to be very rigid about demanding things like [Serializable], [DataContract] or [IXmlSerializable], but they have become a bit more liberal lately.




回答3:


Right now there are really 3 forms of serialization in the .Net Framework.

  1. XmlSerialization - By default works on public fields and properties. Can still be controlled via XmlElementAttribute, XmlAttributeAttribute, etc ...
  2. BinarySerialization - Controlled by the SerializationAttribute. Deeply integrated into the CLR
  3. WCF Seralization - DataContractAttribute, etc ...

There unfortunately is standard overall pattern for serialization. All 3 frameworks have different requirements and quirks.



来源:https://stackoverflow.com/questions/392431/why-doesnt-the-xmlserializer-need-the-type-to-be-marked-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!