反序列化通用列表返回 null
-
21-08-2019 - |
题
我正在反/序列化一个对象,如下所示:
public class myClass : ISerializable
{
public List<OType> value;
public myClass(SerializationInfo info, StreamingContext context)
{
this.value = (List<OType>)info.GetValue("value", typeof(List<OType>));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("value", value, typeof(List<OType>));
}
}
列表中的对象 做 具有可序列化属性。序列化时,不会抛出任何错误,并且列表是 绝不 空,但是当反序列化时,我的所有列表都是空的,我不知道为什么。
我将此标记为 CQ 的回答。我能够生成一个小型的一次性测试应用程序,它可以正确地序列化/反序列化我正在尝试使用的对象,但我似乎仍然无法让它在我的生产代码中工作,但我怀疑它是一些小东西,我我失踪了。
解决方案
那么列表一开始总是空的,你是通过以下方式设置的吗 myClass.value = new List<...>();
?您是否还以二进制和 xml 格式保存了序列化数据,以便可以验证数据是否确实已保存?
还要注意的是,如果您使用 2.0+,如果您不需要控制绝对序列化,则不必实现 ISerialized,您可以将值更改为公共属性,它会自行序列化。
编辑:以下案例似乎对我来说序列化和反序列化效果很好,我发布此内容是为了防止我误解整个问题。
忽略讨厌的测试代码,希望这会有所帮助。
[Serializable]
public class OType
{
public int SomeIdentifier { get; set; }
public string SomeData { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", SomeIdentifier, SomeData);
}
}
[Serializable]
public class MyClass : ISerializable
{
public List<OType> Value;
public MyClass() { }
public MyClass(SerializationInfo info, StreamingContext context)
{
this.Value = (List<OType>)info.GetValue("value", typeof(List<OType>));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("value", Value, typeof(List<OType>));
}
}
...
var x = new MyClass();
x.Value = new OType[] { new OType { SomeIdentifier = 1, SomeData = "Hello" }, new OType { SomeIdentifier = 2, SomeData = "World" } }.ToList();
var xSerialized = serialize(x);
Console.WriteLine("Serialized object is {0}bytes", xSerialized.Length);
var xDeserialized = deserialize<MyClass>(xSerialized);
Console.WriteLine("{0} {1}", xDeserialized.Value[0], xDeserialized.Value[1]);
忘记输出了..
序列化对象为 754bytes
1:你好2:世界
不隶属于 StackOverflow