我有一个foreach循环,并且我在循环内部创建了一个字符串,但是我想在循环外部使用var,有可能吗?使用foreach循环外的foreach循环的变量
List<int> roleIntList = new List<int>();
foreach(var rolenodes in roleIntList){
string myStr = "hello";
}
我有一个foreach循环,并且我在循环内部创建了一个字符串,但是我想在循环外部使用var,有可能吗?使用foreach循环外的foreach循环的变量
List<int> roleIntList = new List<int>();
foreach(var rolenodes in roleIntList){
string myStr = "hello";
}
这是明确不可能的,它也没有声明变量“内部”的foreach循环是一个好主意,你为什么不考虑一下:
List<int> roleIntList = new List<int>();
string myStr;
foreach(var rolenodes in roleIntList){
myStr = "hello";
}
...
//use myStr
每个(类型标识符在表达){ 语句 }
注意:在上述情况下 表示集合元素的迭代变量标识符。当标识符是跟踪参考运算符(C++ Component Extensions)时,您可以修改该元素。执行 其超出范围的每个循环的那一刻完全
见链接 - https://msdn.microsoft.com/en-us/library/ms177202.aspx
我想用户如果要求var rolenodes值被存储并显示在foreach循环之外 –
您正在寻找这样的事情..
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<string> myStr = new List<string>();
List<int> roleIntList = new List<int>();
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();
}
}
}
为什么你需要吗? –
建议回顾一下:https://msdn.microsoft.com/en-us/library/ms973875.aspx – Quintium
在名为“roleIntList”的圆括号内声明的变量仅用于迭代List内的值。这取决于你想要对值做什么,所以我会复制上一个问题,为什么你需要外部变量? – AlexP