Why classes are not serializable by default in .Net?

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

    It is probably better to mark all classes as serializable unless:

    • They will never cross an application domain. If serialization is not required and the class needs to cross an application domain, derive the class from MarshalByRefObject.
    • The class stores special pointers that are only applicable to the current instance of the class. If a class contains unmanaged memory or file handles, for example, ensure these fields are marked as NonSerialized or don't serialize the class at all.
    • Some of the data members contain sensitive information. In this case, it will probably be advisable to implement ISerializable and serialize only the required fields.

    Ref:Object Serialization in the .NET Framework

提交回复
热议问题