我已經調查圍繞這會導致當IComparable的屬性分配的DateTime以下錯誤IComparable的財產的二進制序列化的問題:無法反序列化的IComparable的字段值類型
二進制流「0」不包含有效的BinaryHeader。
下面的代碼會產生這個問題:
/// <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;
}
這種序列化和去:
/// <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 T類型屬性取代了IComparable物業解決問題序列化沒有問題。但是,爲什麼序列化IComparable屬性(當該屬性是DateTime時)首先導致問題,特別是因爲DateTime支持IComparable?這也發生在ISerializable中。
它可能有直接關係的事實,你不能創建接口的實例。 – Bob2Chiv
@ Bob2Chiv當他提供IComparable的實現時,它可以工作。這是一個已知的錯誤。 –
@Adriano有趣的是,我認爲這是因爲你可以序列化一個T的實例,但不是IComparable的一個實例;即使有與之相關的具體價值,就像在這個[問題]中一樣(http://stackoverflow.com/questions/3632769/cannot-serialize-member- because-it-is-an-interface)。然而,很高興知道這個錯誤。 – Bob2Chiv