2013-04-27 77 views
1

有沒有辦法在C#或VB中動態調用循環變量?而不是每個變量的一個一個去?從循環動態調用變量?

想象下面的例子,我想設置dog1Legs,dog2Legs,dog3Legs,有沒有辦法如何從循環調用它們?

String dog1Legs; 
String dog2Legs; 
String dog3Legs; 

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

    dog(i)Legs = "test"; 
} 
+2

這就是所謂的行動的數組,如果你真的想調用。否則,它只是一個數組。 – 2013-04-27 11:42:54

+1

這是[arrays](http://msdn.microsoft.com/zh-cn/library/vstudio/9b9dty7d.aspx)適用的內容。 – GSerg 2013-04-27 11:43:29

+0

我今天問同樣的事情:http://stackoverflow.com/questions/16249823/how-can-i-use-variables-on-variable-name/16250133#16250133 – 1342 2013-04-27 11:45:34

回答

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"; 
    } 
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; } 
} 
+0

感謝您的時間和評論 – Vince 2013-04-27 13:35:04

4

你不需要寫代碼爲

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"); 
} 
+0

雖然這可以工作 - 假設這些是字段,而不是局部變量 - 反射可能不是處理他在這裏需要的最好方法。 – 2013-04-27 12:15:58