在循环外访问变量 [英] accessing variable outside for loop

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

问题描述

如何在for循环之外的for循环中访问分配了一些值的字符串 我可以为您提供方便的代码

how to access a string assigned some value in a for loop, outside the for loop i may provide you with the code for thy convenience

for (Int32 i = 0; i < yourlist.Count; i++)
    {
        String str=(yourlist[i].ToString() + ",");
    }

    String str1 = (str).Substring(0, str.Length - 1);

显示的错误是

名称"str"在当前上下文中不存在

The name 'str' does not exist in the current context

推荐答案

变量的范围不会扩展到循环之外.如果要访问其值,则需要将其保存到更大范围的另一个变量中,如下所示:

The scope of the variable does not extend to outside the loop. If you want to access its value, you need to save it to another variable with a greater scope, like this:

string str;
for (Int32 i = 0; i < yourlist.Count; i++)
{
    str=(yourlist[i].ToString() + ",");
}

String str1 = (str).Substring(0, str.Length - 1);

但是,您可以尝试通过以下方式简单地完成操作:

However, what you are trying to do can be simply done as:

var str1 = string.Join(",", yourlist.Select(o => o.ToString()).ToArray());

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

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