2012-10-31 47 views
1

我想使用變量調用集合內的屬性。我有多個屬性,我不想只爲了獲取信息而使用case語句。這裏是代碼示例vb.net中的變量調用集合屬性

Sub Main() 
    MessageBox("Total: " & GetNum("Total","1")) 
    MessageBox("Night: " & GetNum("Night","1")) 
End Sub 

Private Function GetNum(ByVal pstrProp AS String, ByVal pstrNum AS String) As Double 
    Dim lobjProperties as New Properties 
    'this is where the issue is 
    return lobjProperties."pstrProp"(pstrNum) 
End Function 

Public Class Properties 
    Public ReadOnly Property Total(ByVal pstrNum As String) As Double 
     Get 
      Select Case pstrNum 
       Case "1" 
        Return 48 
       Case "2" 
        Return 30 
       Case Else 
        Return 0 
      End Select 
     End Get 
    End Property 
    Public ReadOnly Property Night(ByVal pstrNum As String) As Double 
     Get 
      Select Case pstrNum 
       Case "1" 
        Return 9 
       Case "2" 
        Return 9 
       Case Else 
        Return 0 
      End Select 
     End Get 
    End Property 
End Class 

任何想法將不勝感激。

回答

0

如果您確實需要確定在運行時調用哪個屬性,那麼使用反射是最佳選擇,但執行該路由的缺點是您會丟失編譯時檢查。如果確定要調用哪個屬性的代碼拼錯了該屬性會怎樣?運行時錯誤和崩潰。

您還可以在您的Properties類中使用字典對象。你可能會建立一個字典對象是這樣的:

Private m_nightValues As New Dictionary(Of String, Double) 
m_nightValues("1") = 9 
m_nightValues("2") = 9 

,並在Night屬性,這樣說

Dim value As Double 
If m_nightValues.TryGetValue(pstrNum, value) Then 
    Return value 
Else 
    Return 0 
End If 

相當有活力,同時保持語法檢查。