动态调用从循环变量? [英] Dynamically call variables from a loop?

查看:124
本文介绍了动态调用从循环变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在C#或VB动态地从一个循环调用变量?而不是通过每一个变量的一个去吗?

想象一下下面的例子,我想设置dog1Legs,dog2Legs,dog3Legs,有没有一种方法如何从一个循环给他们打电话?

 字符串dog1Legs;
字符串dog2Legs;
字符串dog3Legs;

的for(int i = 1; I&4;;我++)
{

    狗(我)腿=测试;
}
 

解决方案

没有,你不能做到这一点。典型的解决方案是词典:

 词典<字符串,字符串>狗=新字典<字符串,字符串>();

  dogs.Add(dog1Legs,NULL);
  dogs.Add(dog2Legs,NULL);
  dogs.Add(dog3Legs,NULL);

  的for(int i = 1; I&4;;我++){
    狗[狗+ i.ToString()+腿] =测试;
  }
 

Is there a way in c# or VB to dynamically call variables from a loop? Instead of going one by one of every variable?

Imagine the following example,I want to set dog1Legs, dog2Legs, dog3Legs, Is there a way how to call them from a loop?

String dog1Legs;
String dog2Legs;
String dog3Legs;

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

    dog(i)Legs = "test";
}

解决方案

No, you can't do this. Typical solution is dictionary:

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

这篇关于动态调用从循环变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆