简体   繁体   中英

XmlInclude All Derived Similarly To Knowtypes Solution in WCF

I have a service method returning BaseModel , which has many derived classes. I wanted my service to be able to get the requested item which ie resolves to DerivedClass1 : BaseModel and return it. Of course the return type of my service would be BaseModel .

In this case I had to add to my BaseModel definition DerivedClass1 as a KnownType

[KnownType(typeof(DerivedClass1))]
[DataContract]
public class BaseModel {
   ...

The list of derived classes is changing and I don't want to always update this, so I found a solution where I can do this:

[KnownType("DerivedTypes")]
[Serializable]
public class BaseModel {
  ...
  private static Type[] DerivedTypes() {
        return (from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(BaseModel)) select t).ToArray();
  }
  ...

So now every derived class is listed as KnownType . Great! Now I would need the same for the needed XmlInclude too. I am using

[System.Xml.Serialization.XmlInclude(typeof(DerivedClass1))]

annotation. Is there a way to do something similar? Is there a better way to do this? Could it be done somehow like

[System.Xml.Serialization.XmlInclude("DerivedTypes")]

Thanks!

如果使用XmlSerializer ,则可以将类型列表传递给其构造函数。

var serializer = new XmlSerializer(typeof(BaseModel), BaseModel.DerivedTypes());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM