我有许多变量,例如
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将被赋予值栏(当x = 1时,foo + x = bar == foo1 = bar)。
有没有办法在C#中执行此操作,还是应该采用其他方法?
答案 0 :(得分:4)
这是不可能的,除非你想使用反射,这不是最好的方法。 在不知道你想要实现什么的情况下,回答有点困难,但你可以创建一个数组来保存你的变量,然后使用x作为索引器来访问它们
for(int x = 0; x < 4; x++)
{
fooarr[x] = bar;
}
答案 1 :(得分:1)
很难判断在你的特定情况下哪种方法最好,但这很可能不是好方法。你绝对需要4个VARIABLES,或者只需要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);
}
答案 2 :(得分:1)
你可以这样做:
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 :(得分:0)
也许替代方法会更好; - )
int[] foo;
// create foo
for(int i = 0; i < 4; i++)
{
foo[i] = value;
}
答案 4 :(得分:0)
如果可能的话,你应该使用包含四个整数的数组。您可以这样声明:
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]