vb.net - 如何在 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 中的名称读取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
我把任何后果留给你:)
推荐阅读
- django - 与用户模型的关系(django)
- pandas - 是否可以在 Pandas 中使用 iterrows 选择多行?
- oracle - 为什么长度(列)和长度b(列)返回相同的长度?
- c - C/C++ 运行时检查失败 #2 - 变量“gradeLetter”周围的堆栈已损坏。Visual Studio 2019。如何解决这个问题?
- heroku - 将 g++ 添加到 heroku 节点服务器
- java - 即使 Activity 被销毁,Android Handler 也会继续运行一段时间
- ruby - 为什么我可以使用 Firefox 或 WGET 访问网站,但无法使用 CURL 或 Ruby
- java - 使用 .class 中的函数或对象 - IntelliJ
- javascript - 从 jsfiddle.net 复制的代码不起作用
- php - 在 laravel 中的 setLocale 之后获取国家/地区的当前日期