Conditional C# Binary Serialization

前端 未结 3 1476
小鲜肉
小鲜肉 2021-01-16 06:32

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

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

[S         


        
相关标签:
3条回答
  • 2021-01-16 06:53

    I wrote a rather simple but extensible framework to solve this sort of problem using bindings. Not sure I completely understand but this is possible:

    public class Class1
    {
      [Ignore]
      public bool IsRemoting { get; set; }
    
      [SerializeWhen("IsRemoting", true)]
      public Class2 B;
    }
    

    http://binaryserializer.codeplex.com

    0 讨论(0)
  • 2021-01-16 06:58
    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 { }
      
    2. 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.

    0 讨论(0)
  • 2021-01-16 07:01
    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.

    0 讨论(0)
提交回复
热议问题