C# 使用for循环遍历变量名

C# 使用for循环遍历变量名,c#,for-loop,variables,variable-initialization,C#,For Loop,Variables,Variable Initialization,我试图使用for循环来迭代一系列变量名,每个变量名的结尾是1到10之间的数字。我已经看到了这个问题的其他一些答案,但无法针对我的具体情况做出任何努力。我的代码如下: string cat2Pos0 = cat2[0]; int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count(); List<int> indexOfPos0 = new List<int>();

我试图使用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;
        }
或:

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

非常感谢,非常感谢您的帮助

Josh

查看如何使用反射进行此操作。(类似于
this.GetType().GetField(“cat”+i.ToString());


但是我真的建议把你的变量改成一个10个变量的数组。因此,
cat
将是一个数组(因为您的
cat
似乎是数组)。

编写一个方法并将cat2[]或cat3[]传递给它,这样做不起作用?
string cat3pos0 = cat3[0];
index = cat3.FindIndex(x => x == cat3Pos0);