循环中的变量 [英] Variables in a loop

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

问题描述

我想知道在for循环中是否有方法将一个值赋值给一个根据其索引号命名的字符串变量?

比方说, 3个字符串变量:

  string message1 = null; 
字符串message2 = null;
字符串message3 = null;

我想让'for'循环做类似下面的代码:



$ p $ for(int i = 1; i <= 3; i ++)
{
messagei =blabla+ i.ToString();



$ b我不想使用if或switch因为它会使代码难以遵循。

有没有办法做到这一点?

解决方案

你不需要3个同名的变量,你想要一个这些变量的数组。

  string [] messages = new string [3]; // 3项数组

然后,您可以将项目存储在数组元素中

  messages [0] =Apple; //数组索引从0开始! 
消息[1] =香蕉;
messages [2] =樱桃;

创建数组的另一种方法是内联数组初始值设定项,保存一些代码

  string [] messages = {Apple,Banana,Cherry}; 

(注意:有更多有效的数组初始化语法。 )

通过一个循环访问它们(foreach)

pre $ $ $ $ c> foreach(消息中的字符串水果)
{
Console.WriteLine(我正在吃一个+水果);

$ / code>

或者

<$ ($ i $ 0 $ i
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ]); //读取值
messages [i] =blabla+ i.ToString(); //写一个值给数组
}


I was wondering whether there's a way in a "for" loop to assign a value to a string variable named according to its index number?

let's say I have 3 string variables called:

string message1 = null;
string message2 = null; 
string message3 = null;

And I want the 'for' loop to do the something like the following code:

 for (int i = 1; i <=3; i++)
 {
   messagei = "blabla" + i.ToString();
 }

I don't want to use an "if" or a "switch" because it will make the code harder to follow.

Is there a way to do that?

解决方案

You don't want 3 variables with the same name, you want an array of those variables.

string[] messages = new string[3]; // 3 item array

You can then store your items in the array elements

messages[0] = "Apple"; // array index starts at 0!
messages[1] = "Banana";
messages[2] = "Cherry"; 

Another way to create that array is an inline array initializer, saves some code

string[] messages = { "Apple", "Banana", "Cherry" }; 

(Note: there are more valid syntaxes for array initialization. Research on the various other methods is left as an exercise.)

And access them via a loop (foreach)

foreach (string fruit in messages)
{
    Console.WriteLine("I'm eating a " + fruit);
}

Or for

for (int i = 0; i < messages.Length; i++)
{
    Console.WriteLine("I'm eating a " + messages[i]); // reading the value
    messages[i] = "blabla" + i.ToString(); // writing a value to the array
}

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

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