DataContract serialization of an inherited type to a base type

I am trying to serialize a class Bas an instance of the ita base class A. DataContractSerializerwon't let me do this.

An example of a failed serialization is as follows:

class Program
{
    [DataContract]
    public class A
    {
        public int Id { get; set; }
    }

    [DataContract]
    public class B : A
    {

    }


    static void Main(string[] args)
    {
        A instance = new B { Id = 42 };

        var dataContractSerializer = new DataContractSerializer(typeof(A));
        var xmlOutput = new StringBuilder();
        using (var writer = XmlWriter.Create(xmlOutput))
        {
            dataContractSerializer.WriteObject(writer, instance);
        }

    }
}

I know that the problem is easy to solve by adding an attribute KnownTypes. However, I want to keep the class Bhidden from the project (do not add the link).

Is it possible to achieve what I want? I tried XmlSerializer, but he gave me the same problem (he added the fully qualified instance type name in XML) and a lot more clunkier to use.

+3
source share
2
[DataContract(Name="YouCannotSeeMyName")]
[KnownTypes(typeof(B))]
public class B : A

<A itype="YouCannotSeeMyName">
  ...
</A>
+3

, . -, , , /.

, B DataContractSerializer .

    class Program
    {
        [DataContract]
        public class A
        {
            public int Id { get; set; }
        }

        [DataContract]
        public class B : A
        {

        }

        static void Main(string[] args)
        {
            A instance = new B { Id = 42 };

            var dataContractSerializer = new DataContractSerializer(typeof(A), new List<Type>() { typeof(B) });
            var xmlOutput = new StringBuilder();
            using (var writer = XmlWriter.Create(xmlOutput))
            {
                dataContractSerializer.WriteObject(writer, instance);
            }

        }
    }

...

<Program.A xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="Program.B"
xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1" />
+1

Source: https://habr.com/ru/post/1779619/


All Articles