簡體   English   中英

序列化接口

[英]Serializing interfaces

我正在嘗試運行類似於此的代碼:

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 ...因為它是一個接口。

XmlInclude不應該解決這個問題嗎?

不可以。您無法序列化界面。 永遠。 它只是告訴你。

界面只不過是對一組行為的描述。 它沒有說明實例的內容。 特別是,雖然實現接口的類的實例必須實現其所有成員,但它肯定具有自己需要序列化的屬性。

它將如何反序列化?

將使用哪個類來反序列化另一端的接口?

這是一個未經測試的陰暗解決方案,我傾向於原則​​上使用:

private IList<Class2> myArray;
[XmlIgnore]
public IList<Class2> MyArray
{
    get { return myArray; }
    set { myArray = value; }
}

[XmlElement("MyArray")]
public object MyArraySerializable
{
    get { return MyArray; }
    set { MyArray = value as IList<Class2>; }
}

這將序列化您可能使用的任何列表作為具有type屬性的通用對象,該屬性將告訴反序列化器對象的實際類型,因此當該對象被反序列化時,它應該再次轉換為IList<Class2> 請記住提供界面可能采用的任何類型。


我認為沒有理由為什么任何序列化程序都無法序列化這些屬性。 它與您實際嘗試序列化接口不同,您嘗試序列化實現某個接口的對象(與抽象子類化差別不大,某些編程語言甚至只能在接口上運行)。

當序列化程序應序列化該對象時, 它知道該對象實現了該接口,它真正需要做的就是序列化它並附加type屬性(就像你通常序列化抽象類或只是超類一樣)。

現在,反序列化器查看類型並可以檢查該對象是否實際上實現了所需的接口,然后將其反序列化為相應的屬性。

或者使用DataContractSerializer

你包括了typeof(List <...>),但是MyArray的類型是IList <...>,它本身沒有明顯的數據結構,但更多的是占位符來獲取一些數據結構。

將MyArray的類型更改為特定類型(例如List),它應該可以工作。

    private List<Class2> myArray;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM