Ste*_*ers 5 c# serialization binary-serialization
我正在/如此序列化一个对象:
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>));
}
}
Run Code Online (Sandbox Code Playgroud)
列表中的对象具有Serializable属性.序列化时,不会抛出任何错误,列表永远不会为空,但是当反序列化我的所有列表都为空时,我不知道为什么.
我将此标记为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]);
Run Code Online (Sandbox Code Playgroud)
忘记输出了..
序列化对象为 754bytes
1:你好2:世界