【问题标题】:Cannot deserialize an IComparable field for value types无法反序列化值类型的 IComparable 字段
【发布时间】: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


【解决方案1】:

【讨论】:

  • 不同的值类型产生不同的结果/异常。如果我传入一个 int 而不是 DateTime,我会收到以下错误 - SerializationException - End of Stream 在解析完成之前遇到。
  • @mmd 是的,也许这取决于数据的反序列化方式,但我同意,这是一件非常愚蠢的事情......
  • 一个已知的结果不一致的错误不是很有帮助!遗憾的是没有计划中的修复并且所涉及的工作超过了收益。 @Adriano - 感谢您提供信息和链接。
猜你喜欢
  • 2023-01-25
  • 2019-08-09
  • 1970-01-01
  • 2022-01-12
  • 2017-03-24
  • 1970-01-01
  • 2017-09-06
  • 2017-10-19
  • 1970-01-01
相关资源
最近更新 更多