DataContract 将继承类型序列化为基类型
我正在尝试将类 B
序列化为 ita 基类 A
的实例。 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));
var xmlOutput = new StringBuilder();
using (var writer = XmlWriter.Create(xmlOutput))
{
dataContractSerializer.WriteObject(writer, instance);
}
}
}
我知道通过添加 KnownTypes
属性可以轻松解决该问题。 但是我想将类 B
从项目中隐藏(不添加引用)。
是否有可能实现我想要的目标?我尝试了 XmlSerializer,但它给了我同样的问题(它在 XML 中添加了完整的实例类型名称),并且使用起来更加笨拙。
I'm trying to serialize class B
as an instance of ita base class A
. The DataContractSerializer
won't allow me to do that.
An example failing the 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 issue is easily resolved by added the KnownTypes
attribute.
However I want to keep the class B
hidden from the project (not add a reference).
Is it at all possible to achieve what I want? I tried the XmlSerializer
but it gave me the same issue (it added the full instance type name in the XML) and is much more clunkier to use.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你会得到
And you will get
我非常确定您无法隐藏合同的某些部分。这类似于处理 Web 服务,其中每一端都必须遵守合同,以了解序列化/反序列化的方式和内容。
此外,您可以在
DataContractSerializer
中传递B
类型,而不是使用该属性。这会给你...
I'm pretty sure that you can't hide portions of the contract. This is akin to dealing with a web service where the contract has to be honored for each end to understand how and what to seriialize/deserialize.
In addition you can pass the
B
type within theDataContractSerializer
versus using the attribute.Which will give you...