在foreach循环外使用foreach循环的变量
我有一个foreach循环,我在循环中创建一个字符串,但我想在循环外使用var,是否可能?
List roleIntList = new List(); foreach(var rolenodes in roleIntList){ string myStr = "hello"; }
如果在循环外声明字符串,则可以:
string myStr = null; List roleIntList = new List (); foreach(var rolenodes in roleIntList){ myStr = "hello"; }
然后,在循环运行后, myStr
将包含最后指定的值。
这绝对不可能,在foreach循环中声明变量“内部”也不是一个好主意,为什么不考虑这个:
List roleIntList = new List (); string myStr; foreach(var rolenodes in roleIntList){ myStr = "hello"; } ... //use myStr
你在寻找像这样的东西..
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { List myStr = new List (); List roleIntList = new List (); roleIntList.Add(1); roleIntList.Add(2); roleIntList.Add(3); roleIntList.Add(4); foreach (var rolenodes in roleIntList) { string ss = rolenodes.ToString(); myStr.Add(ss); } foreach (string s in myStr) { Console.WriteLine(s); } Console.Read(); } } }
for each(表达式中的类型标识符 ){statements}
注意:上述情况下的标识符表示集合元素的迭代变量。 当identifier是跟踪引用运算符(C ++ Component Extensions)时,您可以修改该元素。 超出范围,每个循环的时刻都完全执行