在foreach循环外声明变量 [英] declare variable outside of the foreach loop

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

问题描述

在for循环的情况下,我可以在for语句之外声明索引.例如,代替

In for loop case I can declare the index outside the for statement. For example, instead of

for (int i = 0; i < 8; i++) { }

我可以做到:

int i;
for (i = 0; i < 8; i++) { }

现在与foreach循环相比,我必须在循环内声明变量:

Now in compare to foreach loop, I have to declare the variable inside the loop:

foreach (string name in names) { }

我不能做类似的事情:

string name;
foreach (name in names) { }

之所以困扰我,是因为在循环之后,我想再次使用变量"name".如果发生foreach循环,则不能使用变量名称",因为它在foreach范围之外,并且我无法声明另一个具有相同名称的变量,因为它以前在同一范围内声明过.

The reason this bothers me is that after the loop I want to use the variable "name" again. In case of foreach loop the variable "name" can't be used since it outside of the foreach scope, and I cannot declare another variable with the same name since it declared before in the same scope.

有什么主意吗?

推荐答案

好的,您可以这样做:

string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
    name = loopName;
    // other stuff
}

或更可能:

string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
    if (someCondition.IsTrueFor(loopName)
    {
        name = loopName;
        break;
    }
}

如果foreach循环的内容是 just 来找到一个匹配的元素-可能至少 sounds -那么您应该考虑LINQ是否会更好:

If the contents of the foreach loop is just to find a matching element - which at least sounds likely - then you should consider whether LINQ would be a better match:

string name = names.Where(x => x.StartsWith("Fred"))
                   .FirstOrDefault();

使用LINQ通常可以使代码基本上试图找到更容易阅读的代码.

Using LINQ can often make code which is basically trying to find something a lot simpler to read.

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

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