簡體   English   中英

使用串聯C#引用變量

[英]referencing a variable using concatenation C#

我有很多變量,例如

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#有什么辦法做到這一點,還是我應該采用另一種方法?

除非您想使用反射,否則這是不可能的,這不是最好的方法。 不知道要實現什么目的,很難回答,但是您可以創建一個數組來保存變量,然后使用x作為索引器來訪問它們

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

很難判斷哪種方法在您的特定案例中是最佳方法,但很可能不是最佳方法。 您是否絕對需要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);
}

你能做這樣的事情:

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;
}

也許替代方法會更好;-)

int[] foo;

// create foo

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

如果可能的話,應該使用包含四個整數的數組 您可以這樣聲明:

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]調用foos[3]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM