【问题标题】:Iterating through variable names with for loop [duplicate]使用for循环遍历变量名[重复]
【发布时间】:2020-08-18 05:12:44
【问题描述】:

我正在尝试使用 for 循环来遍历一系列变量名,每个变量名都以 1 到 10 的数字结尾。我已经看到了这个问题的其他一些答案,但无法为我的具体工作做任何工作情况。我的代码如下:

        string cat2Pos0 = cat2[0];
        int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
        List<int> indexOfPos0 = new List<int>();
        bool check = cat2.Contains(cat2Pos0);
        int index = 0;
        if (check == true)
        {
            for (int i = 0; i < numOfPos0; i++)
            {
                index = cat2.FindIndex(x => x == cat2Pos0);
                indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
            }
        }
        else if (cat2Pos0 == "-")
        {
            numOfPos0 = 17;
        }

我需要遍历 10 个变量名称 cat1 - cat10。在代码中:只要有短语“cat”,我就需要能够根据 for 循环来调整它,例如cat1 或 cat5:

string cat3pos0 = cat3[0];

或:

index = cat3.FindIndex(x => x == cat3Pos0);

不幸的是,我无法简单地单独写出每个变体,因为这会占用近 3700 行代码,我希望有更好的方法来实现这一点。

非常感谢,非常感谢所有帮助,

乔什

【问题讨论】:

  • 写一个方法,传入cat2[]或者cat3[],不行吗?

标签: c# for-loop variables variable-initialization


【解决方案1】:

请参阅here 如何为此使用反射。 (类似于this.GetType().GetField("cat" + i.ToString());。)

但我真的建议将您的变量更改为一个包含 10 个变量的数组。所以cat 将是一个数组数组(因为你的cat 似乎是数组)。

【讨论】:

    猜你喜欢
    • 2014-11-28
    • 2015-06-09
    • 2015-03-18
    • 1970-01-01
    • 2016-01-18
    • 2016-02-05
    • 2016-01-14
    • 1970-01-01
    • 2019-12-29
    相关资源
    最近更新 更多