Why classes are not serializable by default in .Net?

后端 未结 5 1586
日久生厌
日久生厌 2021-02-06 23:51

Developers have to \'opt in\' for making classes serializable by explicitly using SerializableAttribute. What could go wrong if classes were serializable by default

5条回答
  •  情话喂你
    2021-02-07 00:29

    IMO [Serializable] is confusing, largely because it is not actually required by most serialization. By that I mean: there is more code using XmlSerializer (includes asmx), DataContractSerializer (includes WCF), JavaScriptSerializer (includes MVC's JsonResult), or things like protobuf-net etc. [Serializable] is mainly BinaryFormatter, which is (from what I see) in definite decline. and with many good reasons.

    As for why: other answers address this, but it doesn't always make sense to serialize something. Sure entity objects can act as DTO, but that is hard to detect in a robust way.

    So IMO there is negligible impact on whether I is [Serializable] or not, but I do agree with the default: you should know that you are planning to serialize something. In some cases this serialization means extra work (particularly as some serializers don't run the ctor/init code, so you need to know to prepare fields appropriately).

提交回复
热议问题