如何使用XmlSerializer序列化具有泛型类的类

时间:2014-08-14 13:42:16

标签: c# xml-serialization

我正在尝试使用XmlSerializer序列化泛型类。

我想序列化TestClass而不管Generic类型,是否可能,我该如何实现?

请指点我一些资源。

    public class CustomAttribute
    {
        public string Key { get; set; }
        public object Value { get; set; }
    }

    public class CustomAttribute<T> : CustomAttribute
    {
        [XmlIgnoreAttribute]
        public new T Value
        {
            get { return (T)base.Value; }
            set { base.Value = value; }
        }
    }

    public class TestClass
    {
        public List<CustomAttribute> AttributeList { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Type[] _extraTypes = new Type[] {typeof (CustomAttribute<string>)};

             var _testClass = new TestClass();

            _testClass.AttributeList = new List<CustomAttribute>();
            _testClass.AttributeList.Add(new CustomAttribute<string>{Key = "TestKey", Value = "a"});

            var serializer = new XmlSerializer(typeof(TestClass), _extraTypes);

            using (Stream str = new MemoryStream())
            {
                serializer.Serialize(str, _testClass);
            }

        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个

    public class CustomAttribute<T> : CustomAttribute
    {
        T _value;

        [XmlIgnoreAttribute]
        public new T Value
        {
            get { return _value; }
            set { base.Value = value;
                _value = value; }
        }
    }

要在序列化时获取所有不同的类型,您可以轻松遍历所有属性并获取其类型:

public static void Main()
{

    var _testClass = new TestClass();

    _testClass.AttributeList.Add(new CustomAttribute<string>{Key = "TestKey", Value = "a"});
    _testClass.AttributeList.Add(new CustomAttribute<int>{Key = "TestKey", Value = 1337});
    _testClass.AttributeList.Add(new CustomAttribute<int>{Key = "TestKey", Value = 1});
    _testClass.AttributeList.Add(new CustomAttribute<int>{Key = "TestKey", Value = 6});
    _testClass.AttributeList.Add(new CustomAttribute<double>{Key = "TestKey", Value = 3.141592654});
    _testClass.AttributeList.Add(new CustomAttribute<string>{Key = "TestKey", Value = "x"});
    _testClass.AttributeList.Add(new CustomAttribute<bool>{Key = "TestKey", Value = true});

    // Build a new list with all the different Types
    List<Type> types = new List<Type>();
    // Loop over all Attributes in _testClass
    foreach (var a in _testClass.AttributeList) {
        // See if this Type is alreadyin the List
        if (types.Contains(a.GetType())) continue;
        // Add it to the List
        types.Add(a.GetType());
    }
    Type[] _extraTypes = types.ToArray();

    var serializer = new XmlSerializer(typeof(TestClass), _extraTypes);

    using (Stream str = new MemoryStream())
    {
        serializer.Serialize(str, _testClass);
    }
}