.NET XML序列化和继承 [英] .NET XML Serialization and inheritance

查看:123
本文介绍了.NET XML序列化和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的结构如下:

public interface A
{
    public void method();
}

public class B : A
{
}

public class C : A
{
}

List<A> list;

列表包含B和C类型的对象,它们还有一些我想保留的字段,可以我现在序列化它,反序列化并获得正确的对象实例?
最好是XML

List contains objects of type B and C they also have some fields that I would like to keep, can I now serialize it, deserialize back and get the proper object instances? Preferably to XML

编辑:

有没有简单的方法来序列化这个包含的列表接口,然后将其反序列化回B和C实例?

Is there any simple way to serialize this list that contains interfaces, and then deserialize it back to B and C instances?

推荐答案

您可以尝试使用 DataContractSerializer

public interface A
{
}

public class B : A
{
}

public class C : A
{
}

class Program
{
    static void Main(string[] args)
    {
        List<A> list = new List<A>(new A[] { new B(), new C() });
        var serializer = new DataContractSerializer(
            list.GetType(), new[] { typeof(B), typeof(C) });

        var sb = new StringBuilder();
        using (var stringWriter = new StringWriter(sb))
        using (var writer = XmlWriter.Create(stringWriter))
        {
            serializer.WriteObject(writer, list);
        }

        using (var stringReader = new StringReader(sb.ToString()))
        using (var reader = XmlReader.Create(stringReader))
        {
            list = (List<A>)serializer.ReadObject(reader);
        }

    }
}

这篇关于.NET XML序列化和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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