.NET binary serialization conditionally without ISerializable
- by SillyWhy
I got 2 classes, for example:
public class A
{
private B b;
...
}
public class B
{
...
}
I need to serialize an object A using BinaryFormatter. When remoting it shall include the field b, but not when serialize to file. Here is what I added:
[Serializable]
public class A : MarshalByRefObject
{
private B b;
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
if (context.State == StreamingContextStates.File)
{
this.b = null;
}
}
...
}
[Serializable]
public class B : MarshalByRefObject
{
...
}
I think this is a bad design because if another class C also contains B, in class C we must add the duplicate OnSerializing() logic as in A. Class B should decide what to do, not class A or C.
I don't want to use ISerializable interface because there are too many variables in class B have to be added to SerializationInfo.
I can create a SerializationSurrogate for class B, which perform nothing in GetObjectData() & SetObjectData(), then use it when serializing to file. However the same maintenance issue because whoever modify class B can't notice what going to happen during serialization & the existence of SerializationSurrogate.
Is there a better alternative?