1

我遇到了一个序列化问题。我的 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 { }

我非常感谢任何可能出错的想法!

问候, 克拉斯

4

1 回答 1

5

您需要将已知类型属性放在基础对象上:

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

或者,如果您不想用这些属性污染您的域模型,您也可以在 web.config 中执行此操作,或使用ServiceKnownTypeService Contract 上的属性

于 2012-06-15T09:27:45.290 回答