1

我正在尝试使用变量调用集合中的属性。我有多个属性,我不想使用 case 语句来获取信息。这是代码示例

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

任何想法将不胜感激。

4

1 回答 1

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

相当动态,同时保留语法检查。

于 2012-10-31T15:13:25.140 回答