Changing types during binary deserialization in C#

半城伤御伤魂 提交于 2019-11-30 23:38:07

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);
    }
}
Konammagari

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!