我调查了有关 IComparable 属性的二进制序列化的问题,当 IComparable 属性被分配一个 DateTime 时,该问题会导致以下错误:
二进制流“0”不包含有效的 BinaryHeader。
以下代码可能会产生此问题:
/// <summary>
/// This class is injected with an icomparable object, which is assigned to a property.
/// If serialized then deserializes using binary serialization, an exception is thrown
/// </summary>
[Serializable]
public class SomeClassNotWorking
{
public SomeClassNotWorking(IComparable property)
{
Property = property;
}
public IComparable Property;
}
public class Program
{
static void Main(string[] args)
{
// var comparable = new SomeClass<DateTime>(DateTime.Today);
// here we pass in a datetime type that inherits IComparable (ISerializable also produces the error!!)
var instance = new SomeClassNotWorking(DateTime.Today);
// now we serialize
var bytes = BinaryHelper.Serialize(instance);
BinaryHelper.WriteToFile("serialisedResults", bytes);
// then deserialize
var readBytes = BinaryHelper.ReadFromFile("serialisedResults");
var obj = BinaryHelper.Deserialize(readBytes);
}
}
我通过将 IComparable 属性替换为实现 IComparable 的类型 T 属性解决了这个问题:
/// <summary>
/// This class contains a generic type property which implements IComparable
/// This serializes and deserializes correctly without error
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
public class SomeClass<T> where T : IComparable
{
public SomeClass(T property)
{
Property = property;
}
public T Property;
}
这可以毫无问题地进行序列化和反序列化。但是,为什么 IComparable 属性的序列化(当该属性是 DateTime 时)首先会导致问题,尤其是在 DateTime 支持 IComparable 的情况下?ISerializable 也会发生这种情况。