我创建了以下变量: count_1 个 count_2 count_3 个 ...
现在我想检查每个变量的条件。
for(int j = 1; j <= 10; j++)
{
if ("count_" + j == 100)
{
...
}
...
}
当然这不起作用,因为“count_”+ j 没有转换成变量。我该怎么做?
最佳答案
你应该使用 List<int>
或 int[]
(数组)代替。它们的存在正是为了这个目的。
您可以在 C# 中执行“动态变量访问”,但不建议(或非常不鼓励)这样做,这很容易出错。
使用数组的例子:
// definition of the array (and initialization with zeros)
int[] counts = new int[10];
// (...)
for(int j = 0; j < counts.Length ; j++) // note that array indices start at 0, not 1.
{
if (count[j] == 100)
{
...
}
...
}
这是一个带有 List<int>
的类似版本:
List
s 更灵活,也稍微复杂一些(它们可以在执行期间改变大小,而数组是固定的,如果你想改变大小,你必须重新创建一个全新的数组。)
// definition of the list (and initialization with zeros)
List<int> counts = new List<int>(new int[10]);
// (...)
foreach (int count in counts) // You can use foreach with the array example above as well, by the way.
{
if (count == 100)
{
...
}
...
}
对于您的测试,您可以像这样初始化数组或列表的值:
int[] counts = new int[] { 23, 45, 100, 234, 56 };
或
List<int> counts = new List<int> { 23, 45, 100, 234, 56 };
请注意,您可以使用 for
或 foreach
对于两个阵列或 List
实际上。这取决于您是否需要在某处跟踪代码的“索引”。
如果您在使用 for
时遇到问题与 List
或 foreach
使用数组,请告诉我。
我记得当我第一次学习编程时,我想做一些像你的 count_1 count_2 等等......希望发现数组和列表的概念能改变我 future 的开发者思维,开辟一个全新的领域。
我希望这会让您走上正确的轨道!
关于c# - 动态访问 for 循环中的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463994/