在C#方法返回布尔 [英] Returning booleans in a C# method

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

问题描述

我有哪些布尔获得由循环填充的数组。拥有该阵列的方法需要返回一个布尔值。因此,我可以做到这一点:

I have an array of booleans which gets filled by a loop. The method that owns the array needs to return a single boolean. So can I do this:

bool[] Booleans = new bool[4];

// do work - fill array

return (Booleans[0] && Booleans[1] && Booleans[2] && Booleans[3]);

所以,如果我有: T,T,F,T 我将获得˚F因为有一回阵列中还是会回送东西或者只是崩溃一起?

So if I have: T,T,F,T will I get F back since there is one in the array or will it send back something else or just crash all together?

推荐答案

一个单一的将导致正与布尔返回逻辑。

A single false will result in false being returned with boolean AND logic.

您也可以改写为:

return Booleans.All(b => b);

有关完整起见,如果LINQ是不是一种选择,你可以通过一个循环实现相同的:

For the sake of completeness, or if LINQ is not an option, you can achieve the same via a loop:

var list = new List<bool> { true, false, true };

bool result = true;
foreach (var item in list)
{
    result &= item;
    if (!item)
        break;
}

Console.WriteLine(result);

有关小样本,你有什么是好的,但由于项目数量的增长无论是上述两种方法将使code友好了许多。

For small samples what you have is fine, but as the number of items grow either of the above approaches will make the code a lot friendlier.

这篇关于在C#方法返回布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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