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.
source
share