Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c# - When is it appropriate to use the KnownType attribute?

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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[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 {}

with a method on the WCF interface that returns:

public Foo GetFoo() { return new 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 {}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...