序列化和还原一个未知的类 [英] Serializing and restoring an unknown class

查看:127
本文介绍了序列化和还原一个未知的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个基地项目包含一个抽象基类Foo。在单独的客户端项目中,有执行该基类的类。

A base project contains an abstract base class Foo. In separate client projects, there are classes implementing that base class.

我想序列化和通过调用基类的一些方法恢复的具体类的一个实例:

I'd like to serialize and restore an instance of a concrete class by calling some method on the base class:

// In the base project:
public abstract class Foo
{
    abstract void Save (string path);
    abstract Foo Load (string path);
}

可以假定在反序列化的时候,所有需要的类是present。如果可能的话以任何方式,序列应该以XML来完成。使基类实现IXmlSerializable的是可能的。

It can be assumed that at the time of deserialization, all needed classes are present. If possible in any way, the serialization should be done in XML. Making the base class implement IXmlSerializable is possible.

我有点困在这里。如果我对事物的理解是正确的,那么这是唯一可能增加一个 [XmlInclude(typeof运算(UnknownClass))] 来为每一个实现类的基类 - 但实现类是未知的!

I'm a bit stuck here. If my understanding of things is correct, then this is only possible by adding an [XmlInclude(typeof(UnknownClass))] to the base class for every implementing class - but the implementing classes are unknown!

有没有办法做到这一点?我有与反思没有经验,但我也用它欢迎的答案。

Is there a way to do this? I've got no experience with reflection, but i also welcome answers using it.

编辑:的问题是的序列化。只是序列化将是一种很容易。 : - )

The problem is Deserializing. Just serializing would be kind of easy. :-)

推荐答案

您也可以做到这一点创造点的的XmlSerializer ,通过提供的其他详细信息构造函数。请注意,它不会重新使用这些模式,所以你要配置的的XmlSerializer 一次(在应用程序启动,从配置),并多次重复使用它...注意更多的自定义选项与 XmlAttributeOverrides 超载...

You can also do this at the point of creating an XmlSerializer, by providing the additional details in the constructor. Note that it doesn't re-use such models, so you'd want to configure the XmlSerializer once (at app startup, from configuration), and re-use it repeatedly... note many more customizations are possible with the XmlAttributeOverrides overload...

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
static class Program
{
    static readonly XmlSerializer ser;
    static Program()
    {
        List<Type> extraTypes = new List<Type>();
        // TODO: read config, or use reflection to
        // look at all assemblies
        extraTypes.Add(typeof(Bar));
        ser = new XmlSerializer(typeof(Foo), extraTypes.ToArray());
    }
    static void Main()
    {
        Foo foo = new Bar();
        MemoryStream ms = new MemoryStream();
        ser.Serialize(ms, foo);
        ms.Position = 0;
        Foo clone = (Foo)ser.Deserialize(ms);
        Console.WriteLine(clone.GetType());
    }
}

public abstract class Foo { }
public class Bar : Foo {}

这篇关于序列化和还原一个未知的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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