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

查看:652
本文介绍了什么时候适合使用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?

此外,还有什么缺点过度使用属性?例如,在previous例如,如果序列化类被打上KnownType(基类),即使有一个明确提及这一类型?

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 /代理生成的类型)的不会知道酒吧 ,然后它会失败。随着属性:

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天全站免登陆