猿问

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

我创建了以下变量:count_1 count_2 count_3...


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


for(int j = 1; j <= 10; j++)

    {

        if ("count_" + j == 100)

        {

        ...

        }

     ...

     }

当然,这不起作用,因为“count_”+ j没有转换为变量。我该怎么做?


当年话下
浏览 84回答 1
1回答

紫衣仙女

您应该改用 a 或 (数组)。它们的存在正是为了这个目的。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++)&nbsp; // note that array indices start at 0, not 1.{&nbsp; &nbsp; if (count[j] == 100)&nbsp; &nbsp; {&nbsp; &nbsp; ...&nbsp; &nbsp; }&nbsp;...&nbsp;}这是一个类似的版本,带有:List<int>Lists 更灵活,也稍微复杂一些(它们在执行期间的大小可能会发生变化,而数组是固定的,如果要更改大小,则必须重新创建一个全新的数组。// definition of the list (and initialization with zeros)List<int> counts = new List<int>(new int[10]);// (...)foreach (int count in counts)&nbsp; // You can use foreach with the array example above as well, by the way.{&nbsp; &nbsp; if (count == 100)&nbsp; &nbsp; {&nbsp; &nbsp; ...&nbsp; &nbsp; }&nbsp;...&nbsp;}对于测试,您可以初始化数组或列表的值,如下所示:&nbsp;int[] counts = new int[] { 23, 45, 100, 234, 56 };或&nbsp;List<int> counts = new List<int> { 23, 45, 100, 234, 56 };请注意,实际上,您可以同时对数组或 s 使用 or。这取决于您是否需要在某个地方跟踪代码的“索引”。forforeachList如果您在使用或与数组一起使用时遇到问题,请告诉我。forListforeach我记得当我第一次学习编程时,我想做一些像你count_1 count_2这样的事情,等等......希望发现数组和列表的概念会改变我的潜在开发人员的想法,打开一个全新的领域。我希望这将使您走上正确的轨道!
随时随地看视频慕课网APP
我要回答