C# 具有布尔返回的方法

C# 具有布尔返回的方法,c#,if-statement,return,C#,If Statement,Return,我正在用bool返回值创建一个方法,但我遇到了一个问题: 这很有效 private bool CheckAll() { //Do stuff return true; } 但是,如果返回值在if语句中,则该方法无法检测它 private bool CheckAll() { if (...) { return true; } } 我怎样才能解决这个问题 private bool CheckAll() { if ( ....) { re

我正在用
bool
返回值创建一个方法,但我遇到了一个问题:

这很有效

private bool CheckAll()
{
  //Do stuff
  return true;
}
但是,如果返回值在if语句中,则该方法无法检测它

private bool CheckAll()
{
  if (...)
  {
    return true;
  }
}
我怎样才能解决这个问题

private bool CheckAll()
{
    if ( ....)
    {
        return true;
    }

    return false;
}
当if条件为false时,该方法不知道应该返回什么值(可能会出现类似“并非所有路径都返回值”的错误)

如果您的if条件为true,那么您可以简单地写下:

private bool CheckAll()
{
    return (your_condition);
}
如果您有副作用,并且希望在返回之前处理这些副作用,则需要第一个(长)版本。

长版本:

private bool booleanMethod () {
    if (your_condition) {
        return true;
    } else {
        return false;
    }
}
但是,由于您使用的是您的病情结果作为方法的结果,因此您可以将其缩短为

private bool booleanMethod () {
    return your_condition;
}
这是我解决问题的方法

使用以下代码:

public bool roomSelected()
{
    foreach (RadioButton rb in GroupBox1.Controls)
    {
        if (rb.Checked == true)
        {
            return true;
        }
    }
    return false;
}

用一种更简单的方式来解释这一点

public bool CheckInputs(int a, int b){
public bool condition = true;

if (a > b || a == b)
{
   condition = false;
}
else
{
   condition = true;
}

return condition;
}

您缺少了else部分。如果所有条件都为false,那么else将在您尚未声明并从else分支返回任何内容的地方工作

private bool CheckALl()
{
  if(condition)
  {
    return true
  }
  else
  {
    return false
  }
}

我敢肯定,当你问这个问题时,这两个选项在C#中都不可用,但现在你可以像下面这样做:

// Return with ternary conditional operator.
private bool CheckAll()
{
    return (your_condition) ? true : false;
}

// Alternatively as an expression bodied method.
private bool CheckAll() => (your_condition) ? true : false;

所有代码分支都应该返回一些值,例如,如果if中的条件为false,编译器不知道在这种情况下返回什么。您应该在if块之外显式指定返回(默认)值。这不会编译。请不要提供无效的C#代码。
// Return with ternary conditional operator.
private bool CheckAll()
{
    return (your_condition) ? true : false;
}

// Alternatively as an expression bodied method.
private bool CheckAll() => (your_condition) ? true : false;