反序列化:类型转换错误(不同版本)
我有一个类序列化到一个文件,即。 myfile01.myfile。我正在使用二进制序列化(不是 xml)。
在此类的版本 1 中,有一个字段“ColoredFont”。这是一个包含字体和颜色的类。
在该类的版本 2 中,类 ColoredFont 发生了更改,并且“Font”字段被“SerializedFont”替换。
现在的问题是:当我想打开版本 1 文件时,出现错误:
Object of type 'System.Drawing.Font' cannot be converted to
type 'Project.SerializableFont'.
我已经使用自定义序列化绑定程序
public class Binder : SerializationBinder {
public override Type BindToType(string assemblyName, string typeName) {
Type tyType = null;
string sShortAssemblyName = assemblyName.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
if (sShortAssemblyName.ToLower() == "project"
|| sShortAssemblyName == "SoftwareV_3.0" )
{
sShortAssemblyName = "SoftwareV_4.0";
}
foreach (Assembly ayAssembly in ayAssemblies) {
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0]) {
tyType = ayAssembly.GetType(typeName);
break;
}
}
return tyType;
}
}
如何告诉反序列化将 System.Drawing.Font 转换为 SerializedFont?
I have a class I serialize to a file, ie. myfile01.myfile. I'm using binary serialization (not xml).
In version 1 of this class, there was a field 'ColoredFont'. This is a class that contains a Font and a Color.
In version 2 of the class, the class ColoredFont was changed, and the 'Font' field was replaced by 'SerializableFont'.
Now the problem: when i want to open version 1 files, I get an error :
Object of type 'System.Drawing.Font' cannot be converted to
type 'Project.SerializableFont'.
I already use a custom serialization binder
public class Binder : SerializationBinder {
public override Type BindToType(string assemblyName, string typeName) {
Type tyType = null;
string sShortAssemblyName = assemblyName.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
if (sShortAssemblyName.ToLower() == "project"
|| sShortAssemblyName == "SoftwareV_3.0" )
{
sShortAssemblyName = "SoftwareV_4.0";
}
foreach (Assembly ayAssembly in ayAssemblies) {
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0]) {
tyType = ayAssembly.GetType(typeName);
break;
}
}
return tyType;
}
}
How I can tell the deserialization to convert System.Drawing.Font to SerializableFont ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对
ColoredFont
类尝试一下:Try this for the
ColoredFont
class :当要求
typename ==System.Drawing.Font
时,您必须返回新类型Project.SerializedFont
。编辑 :
您必须仅比较
Font
和SerializedFont
,因为给定的类型名预计是类的名称,无论命名空间如何,但我不确定。然后返回typeof(SerializedFont)
You must return the new type
Project.SerializableFont
when asked fortypename ==System.Drawing.Font
.EDIT :
You must compare
Font
andSerializableFont
only as the given typename is expected to be the name of the class regardless of the namespace but I'm not sure. Then returntypeof(SerializableFont)