什么时候适合使用KnownType 属性? [英] When is it appropriate to use the KnownType attribute?

查看:30
本文介绍了什么时候适合使用KnownType 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了 MSDN 参考之后,我仍然对什么时候使用KnownType 属性有疑问.我知道该属性将类型信息传达给序列化程序,但什么时候需要这样做?当被序列化的类具有基类类型的引用,并且存在可以设置为这些引用的向上转换派生类时,是否合适?

After reading the MSDN reference, I still have questions about when to use the KnownType attribute. I understand that the attribute communicates type information to the serializer, but when is this needed? Is it appropriate when the class being serialized has references of a base class type, and there are up-cast derivative classes that could be set to those references?

此外,过度使用该属性有什么缺点吗?例如,在前面的例子中,如果序列化类被标记为 knownType(baseClass),即使存在对该类型的显式引用?

Moreover, are there any drawbacks to overusing the attribute? For instance, in the previous example, if the serialized class was marked with KnownType(baseClass) even though there was an explicit reference to that type?

推荐答案

[KnownType] 需要告诉它子类型.使用它的缺点是以下内容不起作用:

[KnownType] is needed to tell it about subtypes. The disadvantage of not using it is that the following won't work:

[DataContract]
class Foo {}

[DataContract]
class Bar : Foo {}

WCF 接口上的一个方法返回:

with a method on the WCF interface that returns:

public Foo GetFoo() { return new Bar(); }

如果没有该属性,序列化程序(尤其是对于 mex/代理生成的类型)不会知道 Bar,并且会失败.带属性:

Without the attribute, the serializer (especially for mex/proxy-generated types) won't know about Bar, and it will fail. With the attribute:

[DataContract, KnownType(typeof(Bar))]
class Foo {}

工作.这仅适用于 DataContractSerializer - 使用 NetDataContractSerializer 您可以以不同的方式获取类型数据.

it will work. This only applies to DataContractSerializer - with NetDataContractSerializer you get the type data in a different way.

这篇关于什么时候适合使用KnownType 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆