When is it appropriate to use the KnownType attribute?

£可爱£侵袭症+ 提交于 2019-11-27 08:12:28

[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.

If you're using XSD "inheritance" in your schema.

You've got it backwards; the KnownTypeAttribute is applied to the base class and names all of the derived classes that might be passed as a reference to the base.

For instance:

...
KnownType(typeof(POBoxAddress))
KnownType(typeof(StreetAddress))
KnownType(typeof(SingleLineAddress))
KnownType(typeof(ParsedAddress))
public abstract class AddressBase
{
    ...
}
chilltemp

The KnownType attribute is necessary when you are serializing non-concrete types such as interfaces or base classes. The WCF serializer must know about all possible implementations of the interface or inherited class. Any implementations that it doesn't know about will cause a serialization exception.

One possable usage can be found in this SO question

It is also useful for cases like below:

[DataContract]
[knownType(typeof(Person))]
public class KeyValue
{
  [DataMember]
  public string key {get; set;}

  [DataMember]
  public string value {get; set;}

  // rest of the code
}

now suppose value contains some object of other class say Person. then this all to work you have to add the knownType(typeof(Person))

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!