【发布时间】:2014-10-21 09:17:08
【问题描述】:
我正在尝试反序列化一些使用旧版本应用程序序列化的对象,以便将它们升级到我在新版本应用程序中使用的新格式。
为了做到这一点,我使用自定义 SerializationBinder 来将旧对象映射到新对象。
我可以通过这种方式迁移我的大部分对象,但是当我的其中一个对象派生自基类时,我遇到了问题。问题是基类中的属性不会被反序列化(只有派生类中的属性会被反序列化)。
我能够将问题缩小为一个简短的独立程序,我将在此处粘贴:
namespace SerializationTest
{
class Program
{
static void Main(string[] args)
{
v1derived first = new v1derived() { a = 1, b = 2, c = 3, d = 4 };
v2derived second = null;
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = new MyBinder();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, first);
ms.Seek(0, SeekOrigin.Begin);
second = (v2derived)bf.Deserialize(ms);
Console.WriteLine("a={0} b={1} c={2} d={3}", second.a, second.b, second.c, second.d);
}
}
class MyBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
if (typeName == "SerializationTest.v1base")
{
return typeof(v2base);
}
if (typeName == "SerializationTest.v1derived")
{
return typeof(v2derived);
}
return null;
}
}
[Serializable]
class v1base
{
public int a { get; set; }
public int b { get; set; }
}
[Serializable]
class v1derived : v1base
{
public int c { get; set; }
public int d { get; set; }
}
[Serializable]
class v2base
{
public int a { get; set; }
public int b { get; set; }
}
[Serializable]
class v2derived : v2base
{
public int c { get; set; }
public int d { get; set; }
}
}
在这个程序中,我正在序列化一个 v1 派生对象,并尝试将其反序列化为一个 v2 派生对象。两个对象完全相同,但程序不会反序列化 a 和 b 属性。
这是我得到的输出: a=0 b=0 c=3 d=4
我认为问题与自动属性有关。如果我删除 {get;set;} 并将它们变成字段,那么它将起作用。但是我的应用程序中的 v1 对象是属性,所以我必须使用它。
所以问题是:我怎样才能让这个反序列化正常工作?
【问题讨论】:
标签: c# .net serialization binary-serialization