1

c# 或 VB 中有没有办法从循环中动态调用变量?而不是逐个变量?

想象一下下面的例子,我想设置 dog1Legs、dog2Legs、dog3Legs,有没有办法从循环中调用它们?

String dog1Legs;
String dog2Legs;
String dog3Legs;

for(int i=1; i<4; i++)
{

    dog(i)Legs = "test";
}
4

3 回答 3

6

您无需将代码编写为

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");
}
于 2013-04-27T12:05:08.857 回答
3

您应该使用数组或列表。例如

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; }
}
于 2013-04-27T11:44:42.960 回答
1

不,你不能这样做。典型的解决方案是字典:

  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";
  }
于 2013-04-27T11:49:53.610 回答