具有抽象 DataMember 数组的 WCF DataContract
我无法让这个场景发挥作用。这是模式 -
[DataContract]
/*abstract*/ class BaseT
{ ... }
[DataContract]
class ChildT : BaseT
{ ... }
[DataContract]
class MessageContents
{
[DataMember]
public BaseT[] XX; // Array of BaseT objects. I need WCF to somehow figure out that they're actually ChildT.
}
// ...receive a webHttp request of type MessageContents...
// cast to use MessageContents.XX as a ChildT[] instead of a BaseT[]
ConcreteClass[] QQ = (ConcreteClass[])request.xx;
我尝试使用 KnownType 或 KnownServiceType 注释几乎所有内容,但无济于事。
如果我将 BaseT 设为抽象,则会收到反序列化错误“无法实例化抽象类”。如果我使 BaseT 具体化,我不会收到反序列化错误。相反,当我将其转换为 ChildT 时,我得到“无法将类型 'BaseT[]' 的对象转换为类型 'ChildT[]'”。
I can't make this scenario work. Here's the pattern-
[DataContract]
/*abstract*/ class BaseT
{ ... }
[DataContract]
class ChildT : BaseT
{ ... }
[DataContract]
class MessageContents
{
[DataMember]
public BaseT[] XX; // Array of BaseT objects. I need WCF to somehow figure out that they're actually ChildT.
}
// ...receive a webHttp request of type MessageContents...
// cast to use MessageContents.XX as a ChildT[] instead of a BaseT[]
ConcreteClass[] QQ = (ConcreteClass[])request.xx;
I've tried annotating practically everything with KnownType or KnownServiceType to no avail.
If I make BaseT abstract, I get a deserialization error 'cannot instance abstract class'. If I make BaseT concrete, I don't get a deserialization error. Instead, when I go to cast it to ChildT, I'm getting "unable to cast object of type 'BaseT[]' to type 'ChildT[]'".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有用 KnownType 标记的 BaseT 对象定义并在那里列出 ChildT,它将与抽象基础一起正常工作(我一直这样做)。您的问题是 C# 中不允许数组协变,因此您无法将 BaseT[] 转换为 ChildT[]。不过,将各个元素转换为 ChildT 是可行的 - 如果您在调试器中检查数组,您可以看到这一点 - 如果您需要 ChildT[],让 LINQ 为您完成这项工作(例如,baseArray.Cast().ToArray() )。
If you have the BaseT object definition tagged with KnownType and list ChildT there, it will work fine with the abstract base (I do this all the time). Your problem is that array covariance isn't allowed in C#, so you can't cast BaseT[] to ChildT[]. Casting the individual elements to ChildT will work, though- you can see this if you inspect the array in the debugger- if you need a ChildT[] let LINQ do the work for you (eg, baseArray.Cast().ToArray()).