我有一个包装类来帮助反序列化传入的json消息。 目前我正在使用它。
Dim oXMessage As XMessage = JsonConvert.DeserializeObject(Of XMessage)(message)
我想为类创建一个构造函数,以便我可以更干净地实例化它。喜欢这个
Dim oXMessage as XMessage = New XMessage(message)
我已经尝试过以下构造函数,但它不起作用。 有人能指出我正确的方向吗?
Public Class XMessage
<JsonProperty("e")> Public MessageType As String
<JsonProperty("data")> Public MessageData As Object
<JsonProperty("ok")> Public MessageOk As String
Public Sub New(message As String)
Me = JsonConvert.DeserializeObject(Of Me)(message)
End Sub
End Class
答案 0 :(得分:0)
Me
关键字引用当前实例,不能作为赋值目标。
相反,您可能想要做的是创建一个新对象,对其进行反序列化,并将新对象成员变量复制到当前实例。
编辑:没有辅助功能
Public Class XMessage
<JsonProperty("e")> Public MessageType As String
<JsonProperty("data")> Public MessageData As Object
<JsonProperty("ok")> Public MessageOk As String
Public Sub New(message As String)
Dim other = JsonConvert.DeserializeObject(Of XMessage)(message)
Me.MessageType = other.MessageType
Me.MessageData = other.MessageData
Me.MessageOk = other.MessageOk
End Sub
End Class
<强>原始强>
Public Class XMessage
<JsonProperty("e")> Public MessageType As String
<JsonProperty("data")> Public MessageData As Object
<JsonProperty("ok")> Public MessageOk As String
Public Sub New(message As String)
Dim other as XMessage= Deserialize(message)
Me.MessageType = other.MessageType
Me.MessageData = other.MessageData
Me.MessageOk = other.MessageOk
End Sub
Public shared Function Deserialize(message as String) as XMessage
return JsonConvert.DeserializeObject(Of XMessage)(message)
End Function
Public Shared Function Serialize(message As XMessage) As String
return JsonConvert.SerializeObject(message)
End Function
End Class
答案 1 :(得分:0)
您无法在构造函数中重新分配Me
的值,因为这是当前正在构造的对象。但您可以致电JsonConvert.PopulateObject()
初始化其内容:
Public Class XMessage
<JsonProperty("e")> Public MessageType As String
<JsonProperty("data")> Public MessageData As Object
<JsonProperty("ok")> Public MessageOk As String
Public Sub New(message As String)
JsonConvert.PopulateObject(message, Me)
End Sub
Public Sub New()
End Sub
End Class
示例fiddle。