我得到一個對象,它必須從一個通用接口繼承,並且它有一個從該接口作爲屬性的列表。如何序列化接口列表?
要序列化它後面的問題,因爲XmlSerialzer無法確定我的MyClass.Items
列表元素中的實際類型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace MyTest
{
public interface IMyInterface
{
string TestProperty { get; set; }
}
public class MyClass : IMyInterface
{
public string TestProperty { get; set; }
public List<IMyInterface> Items { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass() { TestProperty = "Test" };
XmlSerializer xs = new XmlSerializer(typeof(MyClass)); // <- throws System.NotSupportedException
using (XmlWriter xw = XmlWriter.Create("file.xml", new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
Indent = true,
NewLineHandling = NewLineHandling.Entitize
}))
{
xs.Serialize(xw, obj);
}
}
}
}
我如何序列化List<T>
,其中T是一個接口?
稍微偏離主題,你有沒有考慮有兩類:'MyClass的:IMyInterface'和'MyClassList:名單'。純粹是爲了分開責任? –
oleksii
是的,但是1.導致相同的問題,2.在我的範圍內,MyClass將成爲MyClassList。 – modiX
問題是:你爲什麼要[從列表繼承](http://stackoverflow.com/q/5376203/1997232)?不知道你是否遇到過與List <>屬性相同的問題。如果你這樣做,那麼至少你現在可以使用基類而不是接口。如果基類可以序列化自己,那麼你肯定可以序列化基類的數組。 – Sinatr