【发布时间】:2012-05-09 23:22:36
【问题描述】:
我调查了有关 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 也会发生这种情况。
【问题讨论】:
-
这可能与您无法创建接口实例的事实直接相关。
-
@Bob2Chiv 当他提供他的 IComparable 实现时它可以工作。这是一个已知的错误。
-
@Adriano 有趣,我以为是因为你可以序列化 T 的实例,但不能序列化 IComparable 的实例;即使有与之关联的具体值,例如在此question 中。不过,很高兴知道这个错误。
-
@Bob2Chiv 我还是不明白为什么还没有修复!我猜是为了兼容性,但我无法想象如何。无论如何,它似乎只发生在值类型上。
标签: c# .net serialization