2013-10-30 126 views
0

我的WCF服務包含一個類,如: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的」對象,但「新建」子」不是個因此我無法提供參數,並且mTotal將永遠不會被填充。這是一個限制還是我錯過了什麼?

+0

爲DataContract包含無參數構造函數是一個好主意,並且在被調用時讓類有意義,因爲構造函數不會傳遞給客戶端的服務引用代碼。 –

回答

2

您的參數化構造函數僅在服務器端可用,您不能從客戶端調用它。您可以將一個函數添加到您的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 
0

更新你的類中加入另一個參數的構造函數:

<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,無參數構造函數消失,除非你定義一個。

+0

剛剛添加了空構造函數,它似乎沒有任何區別。 – GJKH

1

SOAP Web服務不公開任何特定於OO或.NET的內容。你不能暴露你的構造函數,索引器,事件或類似的東西。

即使當你「暴露」enum,你也沒有真正暴露enum:只有一個字符串類型可以有幾個枚舉的字符串值之一。沒有相應的整數。

您也不能暴露重載的方法,也不能泛型。