在 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");
}
关于c# - 从循环中动态调用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16251690/