ISerializable的和向后兼容性 [英] ISerializable and backward compatibility
问题描述
您好 我要工作的一个旧的应用程序所使用BinaryFormatter的应用程序数据序列化到FILESTREAM(名为data.oldformat的文件说) 没有任何optimizazion主类已被打上属性
hello I have to work an an old application that used binaryFormatter to serialize application data into filestream (say in a file named "data.oldformat") without any optimizazion the main class has been marked with attribute
<serializable()>public MainClass
.......
end class
和序列化code
dim b as new binaryformatter
b.serialize(mystream,mymainclass)
在一个试图优化序列化/反序列化过程中,我只是做了类实现ISerializable接口,并写了一些优化的序列化程序
In an attempt to optimize the serialization/deserialization process I simply made the class implement the ISerializable interface and wrote some optimized serialization routines
<serializable()>public MainClass
implements ISerializable
.......
end class
优化的作品真的很好,但我必须找到一个方法来reatrive里面的旧文件中的数据实现向后兼容。
The optimization works really well but I MUST find a way to reatrive the data inside the old files for backward compatibility.
我怎样才能做到这一点?
How can I do that??
皮耶路易吉
推荐答案
stmax 具有优良的答案,但我会实现它这个样子,它使用 SerializationEntry.GetEnumerator( )
而不是的try / catch
。这种方式是更清洁,显著更快。
stmax has an excellent answer, however I would implement it like this, which uses SerializationEntry.GetEnumerator()
instead of try/catch
. This way is cleaner and significantly faster.
public MainClass(SerializationInfo info, StreamingContext context) {
int version = 0;
foreach (SerializationEntry s in info)
{
if (s.Name == "version")
{
version = (int)s.Value;
break;
}
}
switch (version) {
case 0:
// deserialize "old format"
break;
case 1:
// deserialize "new format, version 1"
break;
default:
throw new NotSupportedException("version " + version + " is not supported.");
}
}
我会preFER使用.FirstOrDefault()LINQ的版本,但SerializationInfo中并没有实现IEnumerable - 在脸上,古怪的是,它甚至没有实现旧IEnumerable接口
I would prefer a LINQ version using .FirstOrDefault(), but SerializationInfo does not implement IEnumerable - in face, weirdly enough, it doesn't even implement the old IEnumerable interface.
这篇关于ISerializable的和向后兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!