gpt4 book ai didi

c# - 无法反序列化值类型的 IComparable 字段

转载 作者:行者123 更新时间:2023-11-30 16:24:45 24 4
gpt4 key购买 nike

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

最佳答案

关于c# - 无法反序列化值类型的 IComparable 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10518206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com