【发布时间】:2018-07-10 13:42:33
【问题描述】:
在名为“application1”的应用程序中,我将此结构序列化为二进制:
namespace namespace1
{
[System.Serializeable]
class ClassA
{
List<ClassB> List
}
}
在名为“application2”的应用程序中,我必须反序列化这个二进制文件,但我的 ClassA 和 ClassB 必须在 namespace2 而不是 namespace1 内。
于是我写了一个序列化活页夹:
public class TypeNameConverter : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
assemblyName = Assembly.GetExecutingAssembly().FullName;
if (typeName.Contains("nemespace1."))
typeName = typeName.Replace("nemespace1.", "nemespace2.");
Type retType = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
return retType;
}
}
我是这样使用它的:
binaryFormatter.Binder = new TypeNameConverter();
(T)binaryFormatter.Deserialize(memoryStream);
这成功地将 namespace1.ClassA 反序列化为 namespace2.ClassA,但是 无法将列表 od nemespace1.ClassB 进一步反序列化为 namespace2.ClassB 列表。我猜它失败了,因为 ClassB 的列表被封装到 ClassA 中并且 BindToType() 函数没有被“内部元素”调用,它只为 ClassA 调用一次,然后尝试反序列化 ClassA 并且无法提取 ClassB 列表并出现错误:
SerializationException: Could not find type
'System.Collections.Generic.List`1[[namespace1.ClassB, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
我不能对 application1 做任何调整(不能改变我做序列化的方式)我只能调整 application2 中的反序列化逻辑。
我正在尝试为这个特定问题找到解决方案,有人遇到过类似的问题,或者对如何解决这个问题有想法吗?
谢谢!
【问题讨论】:
-
您是否考虑过序列化为非二进制格式(如 JSON)?
-
问题是,我无法对我进行序列化的“application1”进行任何调整。我必须找到在不改变序列化方法的情况下反序列化这些数据的方法。感谢您的评论。
标签: c# namespaces binary-deserialization cross-application