我有以下课程:
[Serializable]
public class ExtendedAddressData
{
public String AddressLine1 { get; set; }
public String AddressLine2 { get; set; }
public String Country { get; set; }
public String City { get; set; }
public String Firstname { get; set; }
public String Surname { get; set; }
public String FakeField { get; set; }
}
[Serializable]
public class AddressData
{
public String AddressLine1 { get; set; }
public String AddressLine2 { get; set; }
public String Country { get; set; }
public String City { get; set; }
public String ZipCode { get; set; }
public String Firstname { get; set; }
public String Surname { get; set; }
}
我试图确保旧的 AddressData 在未来仍然可以反序列化,尽管它被序列化了一个稍微不同的类。
基本上,空的(不存在的)字段应该被删除,那些被删除的应该被遗忘。
我正在从 Object 序列化到 Byte[] (并返回)。不是 XML 或 JSON
private static byte[] ObjectToByteArray(object _Object)
{
try
{
var memoryStream = new MemoryStream();
new BinaryFormatter().Serialize(memoryStream, _Object);
return memoryStream.ToArray();
}
catch (Exception e)
{
Console.WriteLine("Exception caught in process: {0}", e);
}
return null;
}
private static object ByteArrayToObject(byte[] aBytes)
{
try
{
var memoryStream = new MemoryStream(aBytes);
var serializedObject = new BinaryFormatter().Deserialize(memoryStream);
return serializedObject;
}
catch (Exception e)
{
Console.WriteLine("Exception caught in process: {0}", e);
}
return null;
}
这是一个简化的 UnitTest,它可能解释了我比我能做的更好的事情
public void LegacySerializationSupportTest()
{
var realData = new AddressData()
{
AddressLine1 = "AddressLine1",
AddressLine2 = "AddressLine2",
City = "City",
Country = "Country",
Firstname = "Firstname",
Surname = "Surname",
ZipCode = "ZipCode"
};
var bytearray = AddressRepository_Accessor.ObjectToByteArray(realData);
AddressData realObject = (AddressData) AddressRepository_Accessor.ByteArrayToObject(bytearray);
ExtendedAddressData fakeObject = (ExtendedAddressData) AddressRepository_Accessor.ByteArrayToObject(bytearray);
Assert.AreEqual(realObject.AddressLine1,fakeObject.AddressLine1);
}
有什么办法可以做到这一点并且仍然使用 bytearray 而不是 JSON 或 XML?