我有下面的类使用BinaryFormatter的序列化到一个文件二进制格式化,并与属性,而无需备份领域
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, new TestClass{ItemOne = "ItemOne", ItemTwo = "ItemTwo"});
fs.Close();
使用此代码时反序列化:
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
TestClass addresses = (TestClass)formatter.Deserialize(fs);
fs.Close();
我得到的一切正常。 不过,现在我需要的类有一些支持字段像这样:
[Serializable]
public class TestClass
{
private string _itemTwo;
private string _itemOne;
public String ItemTwo
{
get { return _itemTwo; }
set { _itemTwo = value; }
}
public String ItemOne
{
get { return _itemOne; }
set { _itemOne = value; }
}
}
我的问题是,现在,出于某种原因,从以前的版本反序列化不工作了。我得到的类,但属性留空。
我不能影响序列化过程或前一个类的状态。
我该如何获取文件反序列化到当前类?
我试过你的代码,它工作正常。 BinaryFormatter不会序列化私有字段,但会对后续字段进行序列化属性。您使用的是哪个版本的.NET? – codingadventures
二进制格式化程序不具有版本容差。你将无法离开老的dll。将旧的和新的.dll文件加载到一个新的项目中并编写一个转换器程序。或者可能是旧的dll来获取它给后台字段的名称。 – RadioSpace
@GiovanniCampo我正在使用4.5。我们有这样一个真实的生活问题,我创建了一个模拟它的小程序,并且它不起作用。 – atlanteh