Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

c# - Variables in a loop

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...