bool返回的方法

Par*_*ard 3 c# if-statement return

我正在制作一个bool返回值的方法,我有一个问题:

这有效

private bool CheckAll()
{
  //Do stuff
  return true;
}
Run Code Online (Sandbox Code Playgroud)

但是这不是,如果它在IF语句中,则该方法无法检测返回值.

private bool CheckAll()
{
  if (...)
  {
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Nad*_*oli 22

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

    return false;
}
Run Code Online (Sandbox Code Playgroud)

当if-condition为false时,该方法不知道应返回什么值(您可能会收到类似"并非所有路径返回值"的错误).

正如CQQL指出,如果你的if条件为真,你的意思是返回true,你可以简单地写:

private bool CheckAll()
{
    return (your_condition);
}
Run Code Online (Sandbox Code Playgroud)

如果您有副作用,并且想要在返回之前处理它们,则需要第一个(长)版本.


CQQ*_*QQL 5

长版:

private bool booleanMethod () {
    if (your_condition) {
        return true;
    } else {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,由于您使用的是您的病情结果作为该方法的结果,因此您可以将其缩短为

private bool booleanMethod () {
    return your_condition;
}
Run Code Online (Sandbox Code Playgroud)