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这样的事情,等等......希望发现数组和列表的概念会改变我的潜在开发人员的想法,打开一个全新的领域。
我希望这将使您走上正确的轨道!
没有找到匹配的内容?试试慕课网站内搜索吧
- 1 回答
- 0 关注
- 69 浏览
添加回答
举报