为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
当年话下 2022-08-20 16:01:06
我创建了以下变量:count_1 count_2 count_3...现在我想检查每个变量的条件。for(int j = 1; j <= 10; j++)    {        if ("count_" + j == 100)        {        ...        }     ...     }当然,这不起作用,因为“count_”+ j没有转换为变量。我该怎么做?

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

您应该改用 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++)  // note that array indices start at 0, not 1.

{

    if (count[j] == 100)

    {

    ...

    }

 ...

 }

这是一个类似的版本,带有: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)  // 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 };

请注意,实际上,您可以同时对数组或 s 使用 or。这取决于您是否需要在某个地方跟踪代码的“索引”。forforeachList


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


我记得当我第一次学习编程时,我想做一些像你count_1 count_2这样的事情,等等......希望发现数组和列表的概念会改变我的潜在开发人员的想法,打开一个全新的领域。


我希望这将使您走上正确的轨道!


查看完整回答
反对 回复 2022-08-20

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号