deserializing a generic list returns null

坚强是说给别人听的谎言 提交于 2019-12-04 07:57:10

Well the list is always empty to begin with, are you setting it via myClass.value = new List<...>(); ? Also have you saved the serialized data in both binary and xml formats so you can verify data is actually being saved?

Just a note as well, if you are using 2.0+ you don't have to implement ISerializable if you don't need to control the absolute serialization, you can change value to a public property and it will serialize on it's own.

Edit: The following case seems to serialize and deserialize fine for me, I am posting this incase I am misunderstanding the question as a whole.

Ignoring the nasty test code, hopefully this helps a little.

    [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]);

Forgot the output..

Serialized object is 754bytes

1: Hello 2: World

When you say that your list is null, do you mean that the list itself is null, or that it filled with null entries? If the latter, then this is a known .Net problem: see my question on the same problem.

Basically, List<T>s are only initialized when they are deserialized; the objects that they contain are only deserialized after the object graph has been deserialized. One way around this is to put any code which requires them in an OnDeserialized method, or one with an [OnDeserializedAttribute]. See MSDN.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!