WCF DataContracts和多态性 [英] WCF DataContracts and Polymorphism

查看:85
本文介绍了WCF DataContracts和多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的.从理论上讲,这应该非常简单.

Here's what I want to do. This should (theoretically) be very simple.

说我有一个带有以下代码(裸露骨骼功能)的WCF服务:

Say I have a WCF service with the following code (bare bones functionality):

<DataContract()>
Public Class BaseObj
    <DataMember()>
    Public ID As Integer
End Class


<DataContract()>
Public Class TestObj1
    Inherits BaseObj

    Public Sub New(ByVal idval As Integer)
        ID = idval
    End Sub

End Class


<DataContract()>
Public Class TestObj2
    Inherits BaseObj

    Public Sub New(ByVal idval As Integer)
        ID = idval
    End Sub

    <DataMember()>
    Public DoNotShow As String = "fail"

End Class

这是我要编写的代码:

<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
Public Function GetCollection(ByVal reqReportID As Integer) As List(Of BaseObj)

    Dim myObjs as New List(Of BaseObj)
    myObjs.add(new TestObj1(1))
    myObjs.add(new TestObj2(2))
    return myObjs

End Function

我希望JSON响应看起来像这样:[{"ID":1},{"ID":2}]

I want the JSON response to look exactly like this: [{"ID":1},{"ID":2}]

现在我当前拥有的代码返回一个空响应(没有引发错误,没有传递任何信息).我可以通过执行以下操作来返回某物:

Now the code that I have currently returns an empty response (no error thrown, no information passed). I can get it to return something by doing this:

<DataContract(), KnownType(GetType(TestObj1)), KnownType(GetType(TestObj2))>
Public Class BaseObj
    <DataMember()>
    Public ID As Integer
End Class

不过,响应会在JSON对象中添加"__type",并且还会在JSON对象中添加"DoNotShow"(不是一件好事).

However the response adds a "__type" to the JSON object, and also adds "DoNotShow" to the JSON object (not a good thing).

这里的问题是我不希望传递每个对象唯一的信息.我只想要通过基类每个对象常见的信息.我无能为力,无法改变它,除非我没有丢失任何东西,否则似乎WCF的作者在创建此对象时就对OO编程抱有非常笨拙的看法.

The problem here is that I do not want to pass information that is unique to each object. I only want information that is common to each object through the base class. Nothing I can do will change it, and unless I am missing something, it seems as though the authors of WCF had a very bassackwards view of OO programming when they created this.

您在SO的任何见解都将不胜感激.

Any insight you here at SO might have would be greatly appreciated.

推荐答案

如果您的集合仅键入BaseObj,则我认为序列化程序不可能生成您要查找的JSON.

If your collection is only typed to BaseObj I don't think it's possible for the serializer to produce the JSON you are looking for.

如果仅生成[{"ID":1},{"ID":2}],则收件人无法区分两种类型.另一端如何确定第一个对象的类型为TestObj1,而第二个对象的类型为TestObj2?

If it were to simply produce [{"ID":1},{"ID":2}], there is no way for the recipient to distinguish between the types. How would the other end determine that the first object is of type TestObj1 but the second object is of type TestObj2?

这篇关于WCF DataContracts和多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆