如何从字符串中分配变量 [英] How can assign a variable from string
本文介绍了如何从字符串中分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我有一个很长的代码。我举一个看起来像下面代码的例子。以下示例包含与我的代码相同的逻辑。
如何用字符串调用变量?
那么如何在循环的第一步中将StrArr1中的StrArr2数组作为变量名调用?
Hello there,
I have a long code. I give an example that looks like code below. The following example contains the same logic as my code.
How can I call a variable with a string?
So how can I call StrArr2 array from StrArr1 as the variable name in the first step of the loop?
Dim StrArr1 As String() = {"StrArr2"}
Dim StrArr2 As String() = {"StrArr3", "StrArr4"}
Dim StrArr3 As String() = {"-1"}
Dim StrArr4 As String() = {"StrArr5"}
Dim StrArr5 As String() = {"-1"}
Dim StrArr = StrArr1
Dim StrList As New List(Of String)
Start:
For Each s As String In StrArr
StrList.Add(s)
If s <> "-1" Then StrArr = s : GoTo Start
Next
我尝试了什么:
如何为StrArr分配值
What I have tried:
How can assign to value to StrArr
推荐答案
我不确定我是否理解正确,但无法以编程方式从字符串创建变量。您可以创建字典(字符串,对象) [ ^ ],它可以保存变量名称及其地址。 />
Not sure i understand you correctly, but there's no way to create variable programmatically from string. You can create a Dictionary(Of String, Object)[^] which can hold variable names and their addresses.
Sub Main
Dim StrArr1 As String() = {"StrArr2"}
Dim StrArr2 As String() = {"StrArr3", "StrArr4"}
Dim StrArr3 As String() = {"-1"}
Dim StrArr4 As String() = {"StrArr5"}
Dim StrArr5 As String() = {"-1"}
Dim StrArr As Object
Dim ListOfVariables As New Dictionary(Of String, Object)
ListOfVariables.Add("StrArr1", StrArr1)
ListOfVariables.Add("StrArr2", StrArr2)
ListOfVariables.Add("StrArr3", StrArr2)
ListOfVariables.Add("StrArr4", StrArr4)
ListOfVariables.Add("StrArr5", StrArr5)
StrArr = ListOfVariables("StrArr2")
For Each s In StrArr
Console.WriteLine(s)
Next
End Sub
退货:
Returns:
StrArr3
StrArr4
也许这样:使用字符串名称调用属性或方法 [ ^ ]
我找到了这个解决方案< a href =http://stackoverflow.com/questions/13726809/dynamically-create-variables-in-vb-net>这里
和Maciej Los一样
I found this solution on here
Like as Maciej Los
Dim StrArr1 As String() = {"StrArr2"}
Dim StrArr2 As String() = {"StrArr3", "StrArr4"}
Dim StrArr3 As String() = {"-1"}
Dim StrArr4 As String() = {"StrArr5"}
Dim StrArr5 As String() = {"-1"}
Dim StrArr = StrArr1
Dim StrList As New List(Of String)
Start:
For Each s As String In StrArr
StrList.Add(s)
Dim variables As New Dictionary(Of String, String())
variables(s) = {"StrArr2"} ' Set the value of the "variable"
If s <> "-1" Then StrArr = variables(s) : GoTo Start
Next
这篇关于如何从字符串中分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文