2010-12-27 4 views
2

TestChild 개체를 포함하는 Test 개체 배열을 직렬화하려고합니다.서브 클래스로 채워진 기본 클래스의 배열을 XML로 직렬화하는 방법은 무엇입니까?

public class Test 
{ 
    public string SomeProperty { get; set; } 
} 

public class TestChild : Test 
{ 
    public string SomeOtherProperty { get; set; } 
} 

class Program 
{ 
    static void Main() 
    { 
     Test[] testArray = new[] 
     { 
      new TestChild { SomeProperty = "test1", SomeOtherProperty = "test2" }, 
      new TestChild { SomeProperty = "test3", SomeOtherProperty = "test4" }, 
      new TestChild { SomeProperty = "test5", SomeOtherProperty = "test6" }, 
     }; 

     XmlSerializer xs = new XmlSerializer(typeof(Test)); 

     using (XmlWriter writer = XmlWriter.Create("test.xml")) 
      xs.Serialize(writer, testArray); 
    } 
} 

TestChild를 Test로 변환 할 수 없다는 InvalidOperationException이 표시됩니다.

이것은 의미가 있지만 어쨌든 그것을 할 수있는 방법이 있습니까?

답변

1

가장 간단한 방법은 주석입니다 (XmlSerializer에 대한 더 복잡한 생성자를 사용하는 경우)를 그렇지 않으면

[XmlInclude(typeof(TestChild))] 
public class Test 
{ 
    public string SomeProperty { get; set; } 
} 

: 클래스가되도록 시리얼 라이저는 서브 클래스를 예상 매우이어야하며 serializer 인스턴스를 캐시하고 재사용해야합니다. 그렇지 않으면 메모리를 낭비합니다 (가비지 수집이 불가능할 때마다 어셈블리를 생성합니다. 가장 간단한 생성자는 단지 Type을 사용하여이 캐싱을 처리합니다.

+0

고마워요! (특히 캐싱에 대한 조언) – neo2862

0

당신은 또한 당신이 테스트 배열 Test[]하지 Test를 직렬화하는의 proper constructor를 사용하여 알려진 유형을 지정할 수 생성자 따라서 첫 번째 인수는 typeof(Test[])해야한다 :

var xs = new XmlSerializer(typeof(Test[]), new Type[] { typeof(TestChild) }); 
관련 문제