XmlSerializer 测试 2

集合

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var f = new XmlSerializer(typeof(TestClass));
            using (var sw = new StringWriter())
            {
                f.Serialize(sw, new TestClass());
                using (var sr = new StringReader(sw.ToString()))
                {
                    var bt = (TestClass) f.Deserialize(sr);
                    Console.WriteLine(bt.ListIdentical());
                }
            }
        }
    }

    public class TestClass
    {
        private List<int> PrivateList;
        public List<int> MyList;

        public bool ListIdentical()
        {
            return PrivateList == MyList;
        }

        public TestClass()
        {
            PrivateList = new List<int>() { 123, 567 };
            MyList = PrivateList;
        }
    }
}

运行结果为 `True` 。实际上,如果把 `MyList` 换成只读属性,只要其值非 null / Nothing,则程序仍可以正常运行。

也就是说,反序列化过程复用了已有的集合实例。 Continue reading “XmlSerializer 测试 2”

Content is available under CC BY-SA 3.0 unless otherwise noted.