如何将XML序列化'类型' [英] How to XML Serialize a 'Type'

查看:117
本文介绍了如何将XML序列化'类型'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何序列化'类型'?

How do I serialize a 'Type'?

我要序列化到XML中有一个属性,它是一类对象的对象。这个想法是,当它被反序列化,我可以创建一个该类型的对象。

I want to serialize to XML an object that has a property that is a type of an object. The idea is that when it is deserialized I can create an object of that type.

public class NewObject
{
}

[XmlRoot]
public class XmlData
{
    private Type t;

    public Type T
    {
        get { return t; }
        set { t = value; }
    }
}
    static void Main(string[] args)
    {
        XmlData data = new XmlData();
        data.T = typeof(NewObject);
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(XmlData));
            try
            {
                using (FileStream fs = new FileStream("test.xml", FileMode.Create))
                {
                    serializer.Serialize(fs, data);
                }
            }
            catch (Exception ex)
            {

            }
        }
        catch (Exception ex)
        {

        }
    }

我得到这个异​​常:
类型ConsoleApplication1.NewObject预计不会了。使用XmlInclude或SoapInclude属性来指定不是静态已知类型的。

I get this exception: "The type ConsoleApplication1.NewObject was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

我在哪里放[XmlInclude]这甚至可能?

Where do I put the [XmlInclude]? Is this even possible?

推荐答案

XML序列化序列化只有公共领域和对象的属性值到一个XML流。 XML序列化不包括类型信息。例如,如果你有一个存在于库命名空间的Book对象,也不能保证,这将是反序列化为同一类型的对象。

XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same type.

来源:的 MSDN:介绍XML序列化

这篇关于如何将XML序列化'类型'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆