无法为值类型反序列化IComparable字段

时间:2012-05-09 14:31:49

标签: c# .net serialization

我已经调查了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也会发生这种情况。