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

前端 未结 3 1316
情话喂你
情话喂你 2020-11-28 12:11

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,

相关标签:
3条回答
  • 2020-11-28 12:46

    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.

    0 讨论(0)
  • 2020-11-28 12:47

    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.

    0 讨论(0)
  • 2020-11-28 12:52

    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.

    0 讨论(0)
提交回复
热议问题