动态访问for循环中的变量名

时间:2019-01-31 15:30:48

标签: c#

我建立以下变量: count_1 count_2 count_3 ...

现在我要检查每一个变量的条件。

for(int j = 1; j <= 10; j++)
    {
        if ("count_" + j == 100)
        {
        ...
        }
     ...
     }

当然,这工作不为“count_” + j不转换成可变。我该怎么办?

1 个答案:

答案 0 :(得分:4)

您应该改用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更加灵活,但稍微复杂一些(它们可以在执行期间的大小期间更改,而数组是固定的,如果要更改大小,则必须重新创建一个全新的数组)

// 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使用foreachList。这取决于您是否需要在某处跟踪代码的“索引”。

如果将forListforeach与数组一起使用时遇到问题,请告诉我。


我记得当我第一次学习编程时,我想做诸如count_1 count_2之类的事情,等等...希望发现数组和列表的概念改变了我的开发者的思维,开辟了一个全新的领域。

我希望这会让您走上正确的轨道!