Why should I not make a class Serializable?
I'm storing some objects in my viewstate and I wa开发者_如何学Gos wondering if there are any disadvantages to making a class Serializable
?
Is it bad practice to make all of the classes Serializable
?
Firstly. Avoid viewstate.
Generally serialization (textual) is used for transferring objects.
You should avoid marking any class as serializable that is not a DTO (Data transfer object) or message class. We do this for several reasons. What ever picks up your class in serialized format may not have the method information (which is in the original assembly) of a non DTO class. Secondly, a class may reference a resource (DB connection, file handle, etc) Do NOT serialize these, since de serialization does not re-establish resource connections and state, unless explicitly designed for, but is still a bad idea.
So in summary: Do NOT serialize when you have contextual methods and storing data for a thrid party to use. (Like a service response with methods is a bad idea). And do NOT serialize when the class contains a resource reference. Keep your serializable object clean from methods as much as possible. This might involve a little re factoring into a service type pattern.
Do serialize DTO's and messages.
This is more of a design choice.
It is a good practice to make all classes that are actually Serializable as Serializable
. I would just use common sense, and set it for those classes that are intended for crossing process boundaries (DTO classes).
So it those classes which:
- All their properties are simple types
- And if they have complex properties, their types themselves are serializable
Marking it as [Serializable]
(or ISerializable
) is necessary for anything using BinaryFormatter
, which may well include viewstate under the default configuration. As for good vs bad practice... well, most classes don't need to be serialized, and IMO even when they are, using BinaryFormatter
is not always the best choice*. And specifically, marking it as both [Serializable]
and [DataContract]
will cause an exception IIRC.
*=actually, IMO BinaryFormatter
is very rarely a good choice, but I might be biased... and I deliberately don't use viewstate ;p
精彩评论