我遇到了序列化问题。我的Silverlight应用程序不期望我的某个属性在业务对象中,并且不知道如何处理它。以前我通过设置KnownTypeAttribute解决了这个问题,如下例所示,但在这种情况下它不起作用。
我曾经这样解决过:
[DataContract(Name = "baseClass")]
public class baseClass { }
[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }
[DataContract(Name = "busObj2")]
[KnownType(typeof(busObj1))]
public class busObj2 : baseClass
{
public busObj1 myObj { get; set; }
}
唯一不同的是,我的结构略有不同,如下所示:
[DataContract(Name = "baseClass")]
public class baseClass { }
[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }
[DataContract(Name = "busObj2")]
[KnownType(typeof(busObj1))]
public class busObj2 : baseClass
{
public busObj1 myObj { get; set; }
}
// This is the class that I want to send via WCF and that cannot be serialized
// because the serializer doesn't expect busObj1.
[DataContract(Name = "busObj3")]
public class busObj3 : busObj2 { }
我非常感谢任何可能出错的想法!
问候,Clas
答案 0 :(得分:5)
您需要将已知的type属性放在基础对象上:
[DataContract(Name = "baseClass")]
[KnownType(typeof(busObj1))]
[KnownType(typeof(busObj2))]
[KnownType(typeof(busObj3))]
[KnownType(typeof(busObj4))]
public class baseClass { }
[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }
[DataContract(Name = "busObj2")]
public class busObj2 : baseClass { }
[DataContract(Name = "busObj3")]
public class busObj3 : busObj1
{
public busObj2 myObj { get; set; }
}
[DataContract(Name = "busObj4")]
public class busObj4 : busObj3 { }
或者如果您不想使用这些属性来污染您的域名模型,您也可以do it in your web.config or use the ServiceKnownType
attribute on your Service Contract。