我在创建一个具有bool返回值的方法时遇到了一个问题:
这是可行的
private bool CheckAll()
{
//Do stuff
return true;
}但这不是这样的,如果返回值在if语句中,则该方法不能检测返回值。
private bool CheckAll()
{
if (...)
{
return true;
}
}我该如何解决这个问题呢?
发布于 2012-09-27 23:18:15
private bool CheckAll()
{
if ( ....)
{
return true;
}
return false;
}当if-condition为false时,该方法不知道应该返回什么值(您可能会得到类似“不是所有路径都返回值”这样的错误)。
作为CQQL pointed out,如果你想在if条件为true时返回true,你可以简单地写下:
private bool CheckAll()
{
return (your_condition);
}如果你有副作用,并且你想在返回之前处理它们,那么第一个(长)版本将是必需的。
发布于 2012-09-27 23:20:07
长版本:
private bool booleanMethod () {
if (your_condition) {
return true;
} else {
return false;
}
}但是,由于您使用的是条件的结果作为方法的结果,因此可以将其缩短为
private bool booleanMethod () {
return your_condition;
}发布于 2014-10-13 01:43:28
public bool roomSelected()
{
int a = 0;
foreach (RadioButton rb in GroupBox1.Controls)
{
if (rb.Checked == true)
{
a = 1;
}
}
if (a == 1)
{
return true;
}
else
{
return false;
}
}这就是我解决问题的方法
https://stackoverflow.com/questions/12624666
复制相似问题