从For循环返回值 [英] Return value from For loop

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

问题描述

我在我的应用程序中有一个listView。我通过项目循环来检查当前选择哪一个,然后返回一个值。由于所有的路径都必须返回一个值,所以我必须在循环之外返回一个值来覆盖for循环的返回值,那么如何在循环之后保留这个值而不覆盖它?



<$ ($ int $ i $ 0 $ i $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b if(listView1.Items [i] .Checked == true)
{
return listView1.Items [i] .Text; //我想保留这个值


//不要用这个覆盖它,但是编译器
//要求我在这里返回一个值
return 错误;

非常感谢您的帮助。谢谢。



PS我已经尝试过使用break之后的if但是没有运气。

解决方案 div>

在编辑:从上面取消我的评论。



您不必担心这一点。只要它在循环中遇到第一个 return ,它将立即返回该值。在这种情况下,循环外部没有任何代码。



顺便说一下,这段代码会更清晰:



<$ p
{
foreach(listView1.Items中的变量)
{
if(item.Checked)return item。文本;

抛出新的InvalidOperationException(没有找到检查项目);





例外是处理错误的一种更习惯的方式,而 foreach 当您只是迭代集合时,循环优先于 for 循环。



同样使用LINQ,你可以得到更简洁:
$ b $ pre $ public string GetItemValue(
{
return listView1.Items.Cast< ListViewItem>()。Single(i => i.Checked).Text;
}


I have a listView in my app. I loop through the items to check which one is currently selected and then return a value. As all paths have to return a value I have to return a value outside the loop which overwrites the for loop return, how do I keep this without overwriting it after the loop?

public string GetItemValue()
{
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        if (listView1.Items[i].Checked == true)
        {
            return listView1.Items[i].Text; // I want to keep this value
        }
     }
     // Without overwriting it with this but the compiler 
     // requires me to return a value here
     return "Error"; 
}

Any help is most appreciated. Thanks.

P.S I have tried using break after the if but no luck.

解决方案

On edit: bringing down my comment from above.

You don't need to worry about this. As soon as it hits the first return inside the loop, it will return immediately with that value. No code outside the loop is ever hit in that case.

Incidentally, this code would be cleaner:

public string GetItemValue()
{
    foreach (var item in listView1.Items)
    {
        if (item.Checked) return item.Text;
    }
    throw new InvalidOperationException("No checked items found");
}

Exceptions are a more idiomatic way of handling errors, and the foreach loop is preferred to a for loop when you're just iterating over collections.

Also using LINQ, you can get even more concise:

public string GetItemValue()
{
    return listView1.Items.Cast<ListViewItem>().Single(i => i.Checked).Text;
}

这篇关于从For循环返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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