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

VB.NET中为变量分配索引并通过For-Next批量赋值的问题

解决VB.NET中用For-Next循环为字符串变量批量赋值的问题

原代码无法实现预期效果的核心原因是:String类型在VB.NET中具有值类型的赋值语义——当你把first_name等变量放入Object数组时,数组中存储的是原变量值的副本,而非对原变量的引用。修改数组元素只会改变副本,不会影响原变量本身。

以下是两种可行的解决方案:

方案一:使用Action委托批量执行赋值操作

通过存储针对每个变量的赋值委托,在循环中调用委托完成赋值,完全替代原有的四条单独赋值语句:

' 定义TextBox对象数组
Dim TextBox_objects() As TextBox = {first_name_TextBox, last_name_TextBox, age_TextBox, weight_TextBox}

' 定义对应每个变量的赋值委托
Dim variableSetters As New List(Of Action(Of String)) From {
    Sub(text) first_name = text,
    Sub(text) last_name = text,
    Sub(text) age = text,
    Sub(text) weight = text
}

' 循环执行赋值逻辑
For i = 0 To TextBox_objects.GetUpperBound(0)
    variableSetters(i)(TextBox_objects(i).Text)
Next

方案二:先批量读取值再分配给变量

如果觉得委托的方式过于复杂,可以先通过循环把所有TextBox的文本存入字符串数组,再将数组中的值分配给对应变量:

Dim TextBox_objects() As TextBox = {first_name_TextBox, last_name_TextBox, age_TextBox, weight_TextBox}
Dim inputValues(TextBox_objects.Length - 1) As String

' 循环读取所有TextBox的文本内容
For i = 0 To TextBox_objects.GetUpperBound(0)
    inputValues(i) = TextBox_objects(i).Text
Next

' 将数组中的值分配给各个变量
first_name = inputValues(0)
last_name = inputValues(1)
age = inputValues(2)
weight = inputValues(3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:42:43