Pregunta

He leído muchos artículos sobre los tipos conocidos y I belive mi ejemplo debería funcionar. Pero no lo hace. Me estoy poniendo la siguiente excepción de deserialización y no entiendo por qué:

error en la línea 1 de posición 2. Elemento 'A' esperaba de espacio de nombres ' http: // esquemas .datacontract.org / 2004/07 / ConsoleApplication2 '.. Se encontró 'Elemento' con el nombre de 'C', espacio de nombres' 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);
        }
    }
}

¿Qué me falta?

¿Fue útil?

Solución

Cambiar la forma de crear serializador. Uso:

var serializer = new DataContractSerializer(typeof(A));

en lugar de a.GetType ();

Funciona. El código XML que se genera es diferente - fue algo como esto:

<C> ...

y ahora es la siguiente:

<A i:type="C"> ...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top