VB.NET隐藏了一个属性成员

时间:2014-02-16 09:13:43

标签: asp.net vb.net

我目前正在处理返回类。问题是我只想在某些条件满足时才显示某个成员。以下是我的代码。我只想在ResponseCode为99时显示ResponseMsg成员,否则它将被隐藏。

Public Class LoginResponse
    Public Property TerminalID As String       
    Public Property ReaderID As String    
    Public Property TransRef As String
    Public Property TransDateTime As String
    Public Property Timeout As Integer
    Public Property ResponseCode As String
    Public Property ResponseMsg As String
    Public Property Cryptogram As String
End Class

2 个答案:

答案 0 :(得分:1)

你不能说我知道。但你可以这样做:

Public Property ResponseMsg
  Get
    If ResponseCode <> SomeCodeValue
      Return _responseCode
    Else
       Return Nothing
    End if
  End Get
End Property

答案 1 :(得分:0)

您可能想要考虑制作专业类。

假设你有基本的LoginResponse

Public Class LoginResponse
    Public Property TerminalID As String       
    Public Property ReaderID As String    
    Public Property TransRef As String
    Public Property TransDateTime As String
    Public Property Timeout As Integer
    Public Property ResponseCode As String
    ' Note: no ResponseMsg here
    Public Property Cryptogram As String
End Class

然后你有一个扩展响应类继承你的基本LoginResponse

Public Class LoginResponseEx : Inherits LoginResponse
     Public Property ResponseMsg As String
End Class

然后,无论你创建那些LoginResponse个对象,你只需创建一个适当的对象。

假设你有一个GetResponse()程序,如:

Public Function GetResponse() As LoginResponse
    Dim result As LoginResponse = Nothing 
    Dim code As Integer = GetSomeCode() 
    ' ... get the other properties 

    ' Say you have a const or something with the appropriate code: SPECIAL_CODE
    If code = SPECIAL_CODE Then
        Dim msg As String = GetSomeMessage()
        result = New LoginResponseEx(..., code, msg, ...) ' have a special Response
    Else
        result = New LoginResponse(..., code, ...) ' have a normal Response
    End If
    Return result
End Function

最后,在检查响应时,您只需检查ResponseCode中是否有特殊值并分别转换对象。

'...
Dim resp as LoginResponse = GetResponse()
If resp.ResponseCode = SPECIAL_CODE Then
    Dim respx as LoginResponseEx = CType(resp, LoginResponseEx)
    Console.WriteLine("ResponseMessage was: " & respx.ResponseMsg
Else
    Console.WriteLine("No ResponseMessage")
End If
'...

通过这种方式,您可以在特殊班级LoginResponse

中使用ResponseMsg 隐藏的基本ResponseLoginEx

注意执行此操作时,您应该考虑如何实现虚拟类。例如这些字段可能必须声明为Protected而不是Private,但我相信你会做得很好。

当然,这也适用于Serializable类。