简体   繁体   中英

referencing a variable using concatenation C#

I have a number of variables such as

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

Now, I have a for loop, going from var x = 0 to 3 (for the 4 variables), and i would like to use x to call the variables like this:

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

so that when x = 1, then my variable foo1 will be assigned the value bar (foo+x = bar == foo1 = bar when x = 1).

Is there any way of doing this in C# or should I take an alternative approach?

This is not possible, unless you wanted to use Reflection, which would not be the best approach. without knowing what you are trying to achieve, it is a little difficult to answer, but you could create an array to hold your variables and then use x as an indexer to access them

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

It's hard to judge what would be the best approach in your particular case, but it's most likely not the good approach. Do you absolutely need 4 VARIABLES, or only 4 values. A simple list, array, or dictionary would do the job:

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

Could you do something like this:

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

Perhaps an alternative approach would be better ;-)

int[] foo;

// create foo

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

If at all possible, you should use an array that contains four integers. You can declare it like so:

int[] foos = new int[4];

Then, in your loop, you should change to the following:

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

By doing this, you will still have four integers; you just access them with foos[n] , where n is the nth variable you want. Keep in mind that the first element of an array is at 0, so to get the 1st variable, you'll call foos[0] , and to access the 4th foo, you'll call foos[3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM