XML序列化的泛型 Dictionary引起的问题 ---- XmlInclude 妙用

使用了网上盛传的SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable 进行序列化Dictionary时,出现了序列化类型与对象实例类型不符的情况,不能序列化。

程序是这样的

 

    public class TestObject
    {
        
public TestObject()
        {

        }
        
public TestObject(Dictionary<A, string> dic)
        {
            
this.dic = new SerializableDictionary<A, string>(dic);
        }

        
public SerializableDictionary<A, string> dic;
    }

    public abstract class A
    {
        
public A()
        {

        }

        
public A(int i)
        {
            
this.i = i;
        }
        
public int i;
    }

    
public class B : A
    {
        
public B()
        {

        }

        
public B(int i)
            : 
base(i)
        {
            str 
= i.ToString();
        }
        
public string str;
    }

 序列化TestObject对象程序:

            Dictionary<A, string> dic = new Dictionary<A, string>();
            dic.Add(
new B(1), "1");
            dic.Add(
new B(2), "2");
            dic.Add(
new B(3), "3");
            dic.Add(
new B(4), "4");
            TestObject obj 
= new TestObject(dic);

            
// Serialize the object to a file.
            XmlTextWriter writer = new XmlTextWriter(@"c:\test.xml"null);
            XmlSerializer serializer 
= new XmlSerializer(typeof(TestObject));
            serializer.Serialize(writer, obj);

 

结果,序列化类型与对象实例类型不符,序列化错误。

如何解决呢?用XmlInclude声明序列化类型,就可解决了。

在基类A上使用XmlInclude属性,代码如下:

 

    [XmlInclude(typeof(B))]
    
public abstract class A
    {
        
public A()
        {

        }

        
public A(int i)
        {
            
this.i = i;
        }
        
public int i;
    }

完成。希望对大家有帮助.

posted @ 2011-06-16 11:05  anya  阅读(1528)  评论(0编辑  收藏  举报