简体   繁体   English

如何为多个类型创建XML序列化器?

[英]How to Create an XML Serializer for More than One Type?

I am using the XmlSerializer like this, 我这样使用XmlSerializer,

XmlSerializer xs = new XmlSerializer(typeof(myType));

Now I have 5 different "myType". 现在,我有5个不同的“ myType”。 How do I pass the specific type dynamically so I don't have to repeat the same code 5 times? 如何动态传递特定类型,而不必重复相同的代码5次?

Try XmlSerializer xs = new XmlSerializer(obj.GetType()); 尝试XmlSerializer xs = new XmlSerializer(obj.GetType()); .

typeof(myType) will not compile unless myType is a type. 除非myType是类型,否则不会编译typeof(myType)。

If you have an instance of the type, you can do instance.GetType(); 如果您有该类型的实例,则可以执行instance.GetType();。

There is not other option im afraid. 我没有其他选择。 You have to specify some type compile time anyway. 无论如何,您必须指定一些类型编译时间。

Another option is to have a generic method. 另一种选择是拥有通用方法。 Consider this example: 考虑以下示例:

static T DeserializeObject<T>(XmlReader reader)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    T t = (T)serializer.Deserialize(reader);
    return t;
}

Using it: 使用它:

static void Main()
{
    string xml = "<Foo><Blah>Hello World</Blah></Foo>";

    using (MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(xml)))
    {
        XmlReader reader = XmlReader.Create(stream);
        Foo foo = DeserializeObject<Foo>(reader);

        Console.WriteLine(foo.Blah);
    }
}

Just create a little function and have the parameter be of type 'Type'. 只需创建一个小函数并使参数的类型为“类型”即可。

    private void SerializeType(Type theType)
    {
        XmlSerializer xs = new XmlSerializer(theType);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM