일반 인터페이스에서 상속해야하는 객체를 얻었으며 해당 인터페이스의 속성 목록을 속성으로 가지고 있습니다.인터페이스 목록을 직렬화하는 방법은 무엇입니까?
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);
}
}
}
}
T는 인터페이스 인 경우 List<T>
을 어떻게 serialize 할 수 있습니까?
을 약간 주제 떨어져, 당신은 두 개의 클래스 고려해이'MyClass의 : IMyInterface'와'MyClassList : 목록'. 순수하게 책임을 분리 할 것인가? –
oleksii
네, 그렇지만 1.는 동일한 문제를 일으키고, 2. MyClass는 내 범위의 컨텍스트에서 MyClassList가됩니다. – modiX
질문 : 왜 [목록에서 상속 받기를 원하십니까?] (http://stackoverflow.com/q/5376203/1997232)? 당신이'List <>'속성과 동일한 문제를 겪고 있는지 확실하지 않습니다. 그렇다면 적어도 인터페이스 대신 기본 클래스를 사용할 수 있습니다. 기본 클래스가 자체를 직렬화 할 수 있으면 확실하게 기본 클래스의 배열을 직렬화 할 수 있습니다. – Sinatr