You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET如何通过字符串格式的变量名获取对应变量的实际值

问题背景

现有VB.NET代码如下:

Public intUserID As Integer = 1500
Function getvalue(variablename As String) As Integer
    Return variablename 
End Function

调用getvalue函数传入变量名字符串"intUserID"时,需要返回变量的实际值1500,而非传入的字符串本身。

解决方案

可通过反射获取变量值,该方案仅适用于目标变量在modDeclarations模块中声明为公共变量的场景,实现代码如下:

Dim VarType As Type = GetType(modDeclarations)
Dim fld As FieldInfo

fld = VarType.GetField(variablename)
If fld IsNot Nothing Then
    ' 模块为静态类型,GetValue参数传入Nothing即可
    Return CInt(fld.GetValue(Nothing))
End If
' 未找到对应变量时的兜底返回值,可根据需求调整
Return -1

注:原示例代码中fld.getvalue(intUserID)的参数写法有误,模块级变量属于静态成员,获取值时不需要传入实例对象,传Nothing即可正常运行。

内容的提问来源于stack exchange,提问作者Sean ZA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 17:36:08