日期:2014-05-20  浏览次数:20789 次

xml序列化时如何序列化Type类型的属性
Hi,

我有一个类,此类有一个属性叫DataType,类型为Type,我想序列化这个类的实例,同样序列化DataType属性,比如输出成这样:
<MyObject>
  ...
  <DateType>System.Int32</DataType>
  ...
</MyObject>
但是会抛出异常(当前我要序列化的对象的DateType属性的值是typeof(int)),而像int,string等这些类型的属性都很正常,这要怎么解决呢?
抛出的异常是:InvalidOperationException
Message: Type System.Int32 may not be used in this context.

Thanks.

------解决方案--------------------
C# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace Demo
{

    public class MyObject
    {
        public string Name { get; set; }
        public string Sex { get; set; }

        [XmlIgnore]
        public Type DataType { get; set; }

        [XmlElement("DataType")]
        public string DataTypeName
        {
            get { return DataType.ToString(); }
            set { DataType = Type.GetType(value); }
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            MyObject obj = new MyObject() {Name = "jim", Sex = "Male", DataType = typeof (int)};
            XmlSerializer serializer = new XmlSerializer(typeof (MyObject));
            MemoryStream ms = new MemoryStream();
            serializer.Serialize(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            StreamReader sr = new StreamReader(ms);
            string xml = sr.ReadToEnd();
            Console.WriteLine(xml);

            ms.Seek(0, SeekOrigin.Begin);
            MyObject obj2 = serializer.Deserialize(ms) as MyObject;

            Console.WriteLine(obj.DataType == obj2.DataType);
            Console.WriteLine(obj.Name == obj2.Name);
            Console.WriteLine(obj.Sex == obj2.Sex);
            Console.ReadLine();
        }
    }
}