views:

90

answers:

2

I am using BinaryFormatter to serialize a class and its variables by condition. For example:

[Serializable]
public class Class1
{
private Class2 B;
...
}

[Serializable]
public class Class2{...}

I want the variable B to be serialized only when remoting time, but not when i serialize it to file storage. Questions:
1) I know that in XmlSerialization we can use [XmlIgnore] and {PropertyName}Specified to ignore the property conditionally. Is that a equivalent method for [NonSerialized]?
2) For a class with [Serializable] attribute, how to ignore it at the runtime?

A: 
  1. There is no such method. You can control serialization by implementing ISerializable, and if you do you will know which serialization context is active (remoting, file etc.)
  2. AFAIK no way to do it, why do you want this?

Generally speaking I advise you against using BinaryFormatter. It is a maintenance headache if there ever was one. Use XML serialization or some kind of protocol buffers.

Anton Tykhyy
felonny
You don't have to implement ISerializable in all classes, only in those where you want customized logic. Protobuf should allow custom serialization, but I'm not positive that it will fit your needs; maybe you'd be better off rethinking your data architecture or generating custom serialization code if your data architecture is regular enough (i.e. there are clear rules about what should be serialized when, and few exceptions).
Anton Tykhyy
A: 
  1. As already mentioned, it doesn't exist. You could code your way out of although it is a bit messy (that is if you don't want to implement the ISerializable interface as already suggested).

    [Serializable]
    public class ClassA
    {
        [OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            //Set BSerialized = B based on context or some internal boolean
            BSerialized = B;
        }
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
            //Clear BSerialized
            BSerialized = null;
        }
        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            //Restore B from BSerialized
            B = BSerialized;
            BSerialized = null;
        }
        [NonSerialized]
        private ClassB B;
        private ClassB BSerialized;
    }
    [Serializable]
    public class ClassB { }
  1. You can't ignore it. You can only change properties on attributes at runtime and since the NonSerialized attribute doesn't take a true / false argument, you cannot do anything about it runtime.
rebel