Why classes are not serializable by default in .Net?

后端 未结 5 1582
日久生厌
日久生厌 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:20

    I would assume that classes are not serializable by default because there's no guarantee that a dump of the object's state to a stream using Reflection even makes sense. What if your object holds an open connection to a database or communication port? Whenever a new object was constructed by deserializing an instance of the previous object, you would end up with a useless object.

    Plus, you have to consider that whenever a class is serializable, the runtime insists that all of its member variables be serializable as well, unless they are explicitly marked otherwise. It's much easier to make serializability an opt in functionality for developers, rather than forcing them to opt out certain members.

    And finally, you might have certain fields in your class that contain private or sensitive information. Having to explicitly mark classes as serializable ensures that you don't accidentally expose the details of something (whether it be the data or your implementation) to the world that you didn't mean to be public.

提交回复
热议问题