Changing types during binary deserialization in C#

后端 未结 2 402
星月不相逢
星月不相逢 2020-12-17 04:22

One of the solutions in our company consumes a 3rd party service. Communication is done through XML messaging. On our end, we generate classes to be used based on XML sche

相关标签:
2条回答
  • 2020-12-17 05:20

    You can handle this situation with ISerializable, however you will need to loop through the deserialized properties using SerializationInfo.GetEnumerator to determine what type of data was actually read from the stream. In addition, you need to be aware that BinaryFormatter serializes fields not properties, so if your class used Auto-Implemented Properties then the name previously stored in the binary stream will be the name of the backing field not the name of the property.

    For instance, say this is your original class:

    [Serializable]
    public class Foo
    {
        public bool Bar { get; set; }
    
        public Foo() { }
    }
    

    Now you want to change Bar to an integer. To serialize or deserialize both old and new BinaryFormatter streams, use the following implementation of ISerializable:

    [Serializable]
    public class Foo : ISerializable
    {
        public int Bar { get; set; }
    
        public Foo() { }
    
        public Foo(SerializationInfo info, StreamingContext context)
        {
            var enumerator = info.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var current = enumerator.Current;
                Debug.WriteLine(string.Format("{0} of type {1}: {2}", current.Name, current.ObjectType, current.Value));
                if (current.Name == "Bar" && current.ObjectType == typeof(int))
                {
                    Bar = (int)current.Value;
                }
                else if (current.Name == "<Bar>k__BackingField" && current.ObjectType == typeof(bool))
                {
                    var old = (bool)current.Value;
                    Bar = (old ? 1 : 0); // Or whatever.
                }
            }
        }
    
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Bar", Bar);
        }
    }
    
    0 讨论(0)
  • 2020-12-17 05:22

    If we convert boolean to integer, that would be either 0 or 1. Can you please try:

    int val=int.Tryparse(myBooleanValue);
    

    Or

    int val= myBooleanValue?1:0;
    
    0 讨论(0)
提交回复
热议问题