【问题标题】:referencing a variable using concatenation C#使用连接 C# 引用变量
【发布时间】:2012-08-07 02:43:08
【问题描述】:

我有许多变量,例如

int foo1;
int foo2;
int foo3;
int foo4;

现在,我有一个 for 循环,从 var x = 0 到 3(对于 4 个变量),我想使用 x 来调用这样的变量:

for(int x = 0; x < 4; x++)
{
    foo+x = bar;
}

这样当 x = 1 时,我的变量 foo1 将被赋值为 bar(当 x = 1 时,foo+x = bar == foo1 = bar)。

在 C# 中有什么方法可以做到这一点,或者我应该采取其他方法吗?

【问题讨论】:

  • 有一种涉及反射的冗长方法,但您应该使用数组 (int[]) 或 List&lt;int&gt;

标签: c# variables concatenation


【解决方案1】:

这是不可能的,除非你想使用反射,这不是最好的方法。 不知道你想要达到什么目标,这有点难以回答,但你可以创建一个数组来保存你的变量,然后使用 x 作为索引器来访问它们

for(int x = 0; x < 4; x++)
{
    fooarr[x] = bar;
}

【讨论】:

  • 感谢大家的所有快速回答,我只是在检查这是否可能,我将使用多维数组而不是像 TimC 建议的那样(看到每个变量实际上是一个数组,而不仅仅是一个int,对此感到抱歉)。再次感谢您的快速帮助
  • @user1275067。不要忘记整数是值类型。如果您为数组值之一分配值类型变量,则对数组值的更改不会影响原始变量。
【解决方案2】:

你可以这样做吗:

var listVariables = new Dictionary<string, int>
                    {
                        { "foo1", 1 },
                        { "foo2", 2 },
                        { "foo3", 3 },
                        { "foo4", 4 },
                    };

for (int x = 1; x <= 4; x++)
{
   listVariables["foo" + x] = bar;
}

【讨论】:

  • 这实际上是个好主意,我忘记了字典,如果事实上是我所问的直接解决方案,非常感谢:)
【解决方案3】:

很难判断在您的特定情况下哪种方法是最佳方法,但这很可能不是好方法。你绝对需要 4 个变量,还是只需要 4 个值。一个简单的列表、数组或字典就可以完成这项工作:

int[] array = new int[4];
List<int> list = new List<int>(4);
List<int, int> dictionary1 = new Dictionary<int, int>(4);
List<string, int> dictionary2 = new Dictionary<string, int>(4);

for(int x = 0; x < 4; x++)
{
    array[x] = bar;
    list[x] = bar;
    dictionary1.Add(x, bar);
    dictionary2.Add("foo" + x.ToString(), bar);
}

【讨论】:

    【解决方案4】:

    也许另一种方法会更好;-)

    int[] foo;
    
    // create foo
    
    for(int i = 0; i < 4; i++)
    {
      foo[i] = value;
    }
    

    【讨论】:

      【解决方案5】:

      如果可能,您应该使用包含四个整数的数组。你可以这样声明:

      int[] foos = new int[4];

      然后,在您的循环中,您应该更改为以下内容:

      for(int i=0;i<foos.Length;i++)
      {
           // Sets the ith foo to bar. Note that array indexes start at 0!
           foos[i] = bar;
      }
      

      通过这样做,你仍然会有四个整数;您只需使用foos[n] 访问它们,其中 n 是您想要的第 n 个变量。请记住,数组的第一个元素位于 0,因此要获取第一个变量,您将调用 foos[0],而要访问第 4 个 foo,您将调用 foos[3]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多