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

标签 c#

我创建了以下变量: 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 };

请注意,您可以使用 forforeach对于两个阵列或 List实际上。这取决于您是否需要在某处跟踪代码的“索引”。

如果您在使用 for 时遇到问题与 Listforeach使用数组,请告诉我。


我记得当我第一次学习编程时,我想做一些像你的 count_1 count_2 等等......希望发现数组和列表的概念能改变我 future 的开发者思维,开辟一个全新的领域。

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

关于c# - 动态访问 for 循环中的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463994/

相关文章:

c# - 如何在没有重定向的情况下在 ASP.NET 中显示自定义 404 页面?

c# - C# 中的 TraceRoute 和 Ping

c# - OpenID,如何开发提供者

c# - 在Visual Studio 2008中调试多线程C#-C++/CLI-C++解决方案: What are these threads?

c# - 如何使音频文件自身重叠?

c# - 继承,没有祖 parent 如何继承父类

c# - 我可以访问 Entity Framework 中 IDbCommandInterceptor 中的实体吗

c# - 如何正确更新 DataGridView,这样 GUI 就不会卡住

c# - 拖放在 DataGrid (WPF) 中不起作用

c# - 如何将二进制图像从桌面应用程序发布到 ashx 处理程序并接收它?