【问题标题】:WCF Class 'New' sub not exposedWCF 类“新”子未公开
【发布时间】:2013-10-30 18:53:22
【问题描述】:

我的 WCF 服务包含如下类:

<DataContract()>
Public Class MyClass
    <DataMember()>
    Public Property MyProperty As Integer
    <DataMember()>
    Public Property MyOtherProperty As Integer
    Private Property mTotal As Integer
    <DataMember()>
    Public ReadOnly Property Total As Integer
        Get
            Return mTotal
        End Get
    End Property
    Public Sub New(prop1 As Integer, prop2 As Integer)
        mTotal = prop1 + prop2
    End Sub
End Class

当我尝试访问该服务时,我可以创建一个新的“MyClass”对象,但“New”子对象没有公开,因此我无法提供参数,并且永远不会填充 mTotal。这是限制还是我遗漏了什么?

【问题讨论】:

  • 最好包含DataContracts 的无参数构造函数,并在调用时使您的类有意义,因为构造函数不会涉及客户端的服务参考代码。跨度>

标签: .net vb.net wcf


【解决方案1】:

您的参数化构造函数仅在服务器端可用,您不能从客户端调用它。您可以向 ServiceContract 添加一个调用该构造函数然后返回结果的函数。我用VB已经好几年了,如果语法不太正确,请原谅我,但这应该给你正确的想法:

<OperationContract()>
Function CreateNewMyClass(prop1 As Integer, prop2 As Integer) as MyClass

实现看起来像这样:

Function CreateNewMyClass(prop1 As Integer, prop2 As Integer) as MyClass
    Return New MyClass(prop1, prop2) 
End Function

【讨论】:

    【解决方案2】:

    SOAP Web 服务不公开任何特定于 OO 或 .NET 的内容。您不能公开您的构造函数、索引器、事件或类似的东西。

    即使您“公开”enum,您并没有真正公开enum:只是一个可以具有多个枚举字符串值之一的字符串类型。没有对应的整数。

    您也不能公开重载方法本身,也不能公开泛型。

    【讨论】:

      【解决方案3】:

      通过添加另一个无参数构造函数来更新您的类:

      <DataContract()>
      Public Class MyClass
          <DataMember()>
          Public Property MyProperty As Integer
          <DataMember()>
          Public Property MyOtherProperty As Integer
          Private Property mTotal As Integer
          <DataMember()>
          Public ReadOnly Property Total As Integer
              Get
                  Return mTotal
              End Get
          End Property
          Public Sub New(prop1 As Integer, prop2 As Integer)
              mTotal = prop1 + prop2
          End Sub
      
         Public Sub New()
           ' default constructor
         End Sub
      End Class
      

      如果您没有显式定义一个默认(无参数)构造函数,VB 会给您一个默认(无参数)构造函数,但是由于您创建了一个接受prop1prop2 的构造函数,所以除非您定义一个,否则无参数构造函数就消失了。

      【讨论】:

      • 刚刚添加了空的构造函数,似乎并没有什么不同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多