c# - 序列化接口(interface)

标签 c# xml-serialization

我正在尝试运行与此类似的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [Serializable]
    [XmlInclude(typeof(List<Class2>))]
    public class Class1
    {
        private IList<Class2> myArray;

        public IList<Class2> MyArray
        {
            get { return myArray; }
            set { myArray = value; }
        }

    }

    public class Class2
    {
        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer ser = new XmlSerializer(typeof(Class1), new Type[] { typeof(List<Class2>) });
            FileStream stream = File.OpenWrite("Data.xml");
            ser.Serialize(stream, new List<Class1>());
            stream.Close();
        }
    }
}

有人可以向我解释我做错了什么吗?

我得到一个:

无法序列化成员 .. MyArray ...,因为它是一个接口(interface)。

XmlInclude 不应该解决这个问题吗?

最佳答案

没有。您不能序列化接口(interface)。曾经。它只是告诉你。

界面只不过是一组行为的描述。它没有说明实例的内容。特别是,虽然实现接口(interface)的类的实例必须实现其所有成员,但它肯定会有自己的属性需要序列化。

如何反序列化?

将使用什么类来反序列化另一端的接口(interface)?

关于c# - 序列化接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4659248/

相关文章:

java - 如何编写XStream转换器,通过转换为中间对象进行读写?

c# - 多态类型和 IXmlSerializable

c# - 组合框输入事件 WPF

c# - 如何重载 MVC HtmlHelper 扩展方法

c# - 按值更改字典键

c# - 在使用 XmlSerializer 序列化期间排除对象

android - 是否可以同时使用 JAXB 和简单 XML?

c# - 如何在 xml 序列化期间找到循环引用?

c# - 对于一系列可配置的步骤来说,什么是好的设计模式

javascript - GridView 中的 ASP.NET Javascript 值在回发之间丢失