在for(I ..)循环中定义变量 [英] Define variable inside a for(I ..) loop

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

问题描述

hi


我应该怎么做这个工作?



hi
how should i do this work?

string s1;
string s2;
string s3;





i想在里面定义变量循环:





i want to define variable inside of loop:

for (i=1;i=3;i++)
{
   string s+i.tostring();
}





s + i.tostring()是错了。



谢谢



我的尝试:



i不知道该怎么办



help



but s+i.tostring() is wrong.

thanks

What I have tried:

i don't know what should i do

help

推荐答案

它是这样的:

It goes like this:
for (var i = 1; i <= 3; i++)
{
    var myString = "s" + i;
}


TheRealSteveJudge是对的,但是...整个循环是没有意义的,如变量将超出范围的结尾循环并将被丢弃。



更好的解决方案是:

TheRealSteveJudge is right, but ... the whole loop is pointless as shown as the variable will go out of scope at the end of the loop and will be thrown away.

A better solution would be this:
string s = "";
for (int i = 1; i <= 3; i++)
   {
   s = s + i.ToString();
   }
Console.WriteLine(s);

或更大的循环:

Or for larger loops:

StringBuilder sb = "";
for (int i = 1; i <= 3; i++)
   {
   sb.Append(i.ToString());
   }
Console.WriteLine(sb.ToString());

因为字符串是不可变的 - 当您连接字符串时,您创建一个新字符串并且必须复制所有信息 - 如果你不小心,它在处理器能力和内存方面会变得极其低效。 StringBuilder类通过作为可扩展字符串将其减少到最小。

As strings are immutable - when you concatenate strings you create a new string and have to copy all the info across - it can get incredibly inefficient in terms of processor power and memory if you aren't careful. The StringBuilder class reduces that to a minimum by being an expandable string.


如果您正在尝试定义一些名为s1,s2和s3的字符串变量,那将无法工作。你不能在运行时定义这样的变量名。



你可以定义一个包含字符串的集合,例如:

If you're trying to define some string variables named s1, s2, and s3, that's not going to work. You cannot define variable names like that at runtime.

You can define a collection that will hold strings, for example:
List<string> myStrings = new List<string>();
myStrings.Add("some string content");



或字符串数​​组:


or an array of strings:

string[] myStrings = new string[3];
myStrings[0] = "some string content";



有多种方法可以存放一系列商品。您通常不为每个项目定义单个变量。


There's variety of ways of holding a collection of items. You don't normally define a single variable for each item.


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

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