2014-02-16 147 views
1

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

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 
+0

为什么不直接返回空字符串,当Responsecode!= 99并在文档中声明该事实? –

+1

或者更改你的软件结构,这样你就可以拥有一个名为LoginResponseXYZ的类,它继承了LoginResponse类并公开了ResponseMsg成员。 – Mino

+0

我知道这通过返回空字符串,但是这可能隐藏ResponseMsg当ResponseCode!= 99?谢谢 – user3051461

回答

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一个特殊值,并把对象respectivly响应最后,当。

'... 
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类,当然。

1

你不能说我知道。但是你可以做这样的事情:

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

我在考虑设计:如果ResponseCode不符合某些条件,如果ResponseClass并不意味着有'ResponseMsg',那么抛出'Exception'而不是返回' Nothing'。因此,类的用户必须在得到* ResponseMessage之前检查'ResponseCode',以避免**未处理的**异常。这不是** Exceptions **的用途吗? :) – MrPaulch