DataContractSerializer, 알려진 유형 및 상속
-
19-09-2019 - |
문제
알려진 유형에 대한 많은 기사를 읽었으며 내 예제가 작동해야한다고 믿습니다. 그러나 그렇지 않습니다. 사막화에 대한 다음과 같은 예외를 얻고 있으며 이유를 이해하지 못합니다.
1 행 1 위치의 오류 2. 예상 요소 'A'네임 스페이스에서 ''http://schemas.datacontract.org/2004/07/consoleapplication2'..'C ', 네임 스페이스'가있는 '요소'만남http://schemas.datacontract.org/2004/07/consoleapplication2'.
using System;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
namespace ConsoleApplication2
{
[DataContract][KnownType(typeof(C))]class A { }
[DataContract]class C : A { }
class Program
{
static void Main(string[] args)
{
A a = new C();
string data;
var serializer = new DataContractSerializer(a.GetType());
using (var sw = new StringWriter())
{
using (var xw = new XmlTextWriter(sw))
serializer.WriteObject(xw, a);
data = sw.ToString();
}
serializer = new DataContractSerializer(typeof(A));
using (var sr = new StringReader(data))
using (var xr = new XmlTextReader(sr))
a = (A)serializer.ReadObject(xr);
}
}
}
내가 무엇을 놓치고 있습니까?
해결책
시리얼 라이저를 만드는 방식을 변경하십시오. 사용:
var serializer = new DataContractSerializer(typeof(A));
a.getType () 대신;
효과가있다. 생성 된 XML은 다릅니다.
<C> ...
그리고 지금은 다음과 같습니다.
<A i:type="C"> ...
제휴하지 않습니다 StackOverflow