首页 > 解决方案 > 如何在 VB.net 中动态编译代码?动态检索成员变量名

问题描述

例如,如果我有这样的代码

Private Function getCompleteAddress(ByVal sCountryCode as String, ByVal sStateCode as 
String, ByVal sCityCode as String) as String

    If sCountryCode ="US" 
          If StateCode = "AL"
             If CitiCode = "BHM"
                   getCompleteAddress=AddressBook.USALBHM
             End If
           ElseIf StateCode = "WA"
             If CitiCode = "SEA"
                   getCompleteAddress=AddressBook.USWASEA
             End If
           ElseIf StateCode = "ME"
             If CitiCode = "PWM"
                   getCompleteAddress=AddressBook.USMEPWM
             End If
           ElseIf StateCode = "PA"
             If CitiCode = "PHL"
                   getCompleteAddress=AddressBook.USPAPHL
             End If
           ElseIf
                ......
           ElseIf
                ......
End Function

我希望代码看起来像这样

Private Function getCompleteAddress(ByVal sCountryCode as String, ByVal sStateCode as 
String, ByVal sCityCode as String)
 
Dim sCombinedCode as String = sCountryCode + sStateCode + CityCode
getCompleteAddress = AddressBook.sCominedCode
    
End Function

可能吗?请注意 sCombinedCode 不是 AddressBook 的成员,它只是我想象的一种生成更简洁代码的方式。

标签: vb.net

解决方案


使用 vb.net 中的名称读取Access 属性

您可以使用

Private Function getCompleteAddress(ByVal sCountryCode As String, ByVal sStateCode As 
String, ByVal sCityCode as String)
 
Dim sCombinedCode As String = sCountryCode + sStateCode + CityCode
    getCompleteAddress = CallByName(AddressBook, sCountryCode & sStateCode & CityCode, Microsoft.VisualBasic.CallType.Get, Nothing)
End Function

或者

Module Module1
    Public Class AddressBookClass
        Public Property USALBHM As String = "USALBHM"
        Public Property USWASEA As String = "USWASEA"
        Public Function GetPropertyValue(ByVal obj As Object, ByVal PropName As String) As Object
            Dim objType As Type = obj.GetType()
            Dim pInfo As System.Reflection.PropertyInfo = objType.GetProperty(PropName)
            Dim PropValue As Object = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
            Return PropValue
        End Function
    End Class

    Sub Main()
        Dim AddressBook As New AddressBookClass
        Console.WriteLine(AddressBook.GetPropertyValue(AddressBook, "USALBHM"))
        Console.ReadLine()
    End Sub
End Module

我把任何后果留给你:)


推荐阅读