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

前端 未结 3 1346
情话喂你
情话喂你 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: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.

提交回复
热议问题