c# 或 VB 中有没有办法从循环中动态调用变量?而不是逐个变量?
想象一下下面的例子,我想设置 dog1Legs、dog2Legs、dog3Legs,有没有办法从循环中调用它们?
String dog1Legs;
String dog2Legs;
String dog3Legs;
for(int i=1; i<4; i++)
{
dog(i)Legs = "test";
}
您无需将代码编写为
String dog1Legs;
String dog2Legs;
String dog3Legs;
for (int i=1; i<4; i++)
{
FieldInfo z = this.GetType().GetField("dog" + i + "Legs");
object p = (object)this;
z.SetValue(p, "test");
}
您应该使用数组或列表。例如
var dogLegs = new String[3];
for(int i=0; i<dogLegs.Length; i++)
{
dogLegs[i] = "test";
}
或者Dog
上课可能有意义,例如
void Main()
{
var dogs = new List<Dog>();
dogs.Add(new Dog { Name = "Max", Breed = "Mutt", Legs = 4 });
foreach (var dog in dogs)
{
// do something
}
}
class Dog
{
public int Legs { get; set; }
public string Breed { get; set; }
public string Name { get; set; }
}
不,你不能这样做。典型的解决方案是字典:
Dictionary<String, String> dogs = new Dictionary<String, String>();
dogs.Add("dog1Legs", null);
dogs.Add("dog2Legs", null);
dogs.Add("dog3Legs", null);
for(int i = 1; i < 4; i++) {
dogs["dogs" + i.ToString() + "Legs"] = "test";
}