序列化接口 [英] Serializing interfaces

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

问题描述

我试图运行与此类似code:

I'm trying to run code similar to this:

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();
        }
    }
}

谁能给我解释一下我做错了?

Can somebody explain to me what am I doing wrong?

我得到一个:

无法序列成员.. ... MYARRAY,因为它是一个接口。

Cannot serialize member .. MyArray ... because it is an interface.

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

Shouldn't the XmlInclude resolve this?

推荐答案

没有。你不能序列化的接口。永远。它只是告诉你。

No. You can't serialize an interface. Ever. It just told you that.

这是界面只不过一组行为的描述了。它没有提到一个实例的内容。特别是,虽然一个类的实例,实现接口必须实现所有成员,就肯定有它需要被序列化其自身的属性。

An interface is nothing more than a description of a set of behaviors. It says nothing about the contents of an instance. In particular, although an instance of a class implementing an interface must implement all of its members, it will certainly have properties of its own which need to be serialized.

会是怎样反序列化?

什么类将用于反序列化的另一端的接口?

What class would be used to deserialize the interface on the other side?

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

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