代码改变世界

Serialization,Serialize未知类型的对象

2011-03-14 10:29  Dirichlet  阅读(241)  评论(0编辑  收藏  举报
1.下面的实例code中public object ObjectValue { get; set; },不知道其具体的类型,但是仍然可以进行序列化和反序列化。
2. 成员变量加Attribute [XmlElement("Value")]可以在序列化时改变节点的名字,如果不加这个attribute,序列化后的相关xml的节点名字就是成员变量的名字。
   成员变量加[XmlIgnore]表示该成员变量不参与序列化/反序列化。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace serialization
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(TemplateDescription[]));
            StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);

            List<TemplateDescription> list = new List<TemplateDescription>();
            TemplateDescription template = new TemplateDescription("aaa", "bbb", 100);
            template.ObjectValue = new int[2] { 1, 2 };

            list.Add(template);

            // Serrilize
            serializer.Serialize(writer, list.ToArray());
            File.WriteAllText(@"d:\serialize.txt", writer.ToString());
            Console.WriteLine(writer.ToString());

            // DeSerialize
            TemplateDescription[] test = (TemplateDescription[])serializer.Deserialize(new StringReader(writer.ToString()));
            Console.WriteLine(test[0].ToString());

            // 输出结果参考
            /*
            <?xml version="1.0" encoding="utf-16"?>
<ArrayOfTemplateDescription xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TemplateDescription>
    <Name>aaa</Name>
    <Description>bbb</Description>
    <ID>100</ID>
    <Value xsi:type="ArrayOfInt">
      <int>1</int>
      <int>2</int>
    </Value>
  </TemplateDescription>
</ArrayOfTemplateDescription>
serialization.TemplateDescription
            */
        }
    }

    [XmlInclude(typeof(int[]))]
    public class TemplateDescription
    {
        public TemplateDescription()
        {
            this.Name = string.Empty;
            this.Description = string.Empty;
            this.ID = 0;
            this.ObjectValue = null;
        }

        public TemplateDescription(string name, string description, int id)
        {
            this.Name = name;
            this.Description = description;
            this.ID = id;
        }

        public string Name { get; set; }

        public string Description { get; set; }

        public int ID { get; set; }

        [XmlElement("Value")]
        public object ObjectValue { get; set; }

        [XmlIgnore]
        public int[] IntegerArrayValue
        {
            get { return (int[])ObjectValue; }
            set { ObjectValue = value; }
        }

        [XmlIgnore]
        public byte[] ByteArrayValue
        {
            get { return (byte[])ObjectValue; }
            set { ObjectValue = value; }
        }
    }
}