C# 如何检查方法是否返回true

C# 如何检查方法是否返回true,c#,oop,C#,Oop,如何在我的主方法中检查这是否返回true或false?一个代码示例会很有帮助 布尔值是否有我应该知道的默认值 你只需要做如下事情: Public bool SqlCheck(string username, string password) { // sql checks here return true } 如果您不需要测试后的结果,您只需: bool result = SqlCheck(username, password); if (result) { /

如何在我的主方法中检查这是否返回true或false?一个代码示例会很有帮助


布尔值是否有我应该知道的默认值

你只需要做如下事情:

Public bool SqlCheck(string username, string password) 
{
    // sql checks here 
    return true
} 
如果您不需要测试后的结果,您只需:

bool result = SqlCheck(username, password);

if (result)
{
    // Worked!
}
else
{
    // Failed
}
bool
默认为
false

如下所示:

if (SqlCheck(username, password))
{
    // Worked!
}
else
{
    // Failed
}
描述
IF
子句需要一个布尔值(true或false),以便

MSDNif语句根据布尔表达式的值选择要执行的语句

样品 如果以后需要结果,可以将其保存到变量中。

 if (SqlCheck("UserName", "Password"))
 {
     // SqlCheck returns true
 }
 else 
 {
     // SqlCheck returns false
 } 


public bool SqlCheck(string username, string password) 
{
 // sql checks here 
    return true;
} 
更多信息
我不是C#程序员,但我可以想象,当您在
main
方法中调用此方法时,它将返回
SqlCheck
的返回值,不是吗

伪代码:

 bool sqlCheckResult= SqlCheck("UserName", "Password");
 if (sqlCheckResult)
 {
     // SqlCheck returns true
 }
 else 
 {
     // SqlCheck returns false
 } 

 // do something with your sqlCheckResult variable

Boolean是一种系统类型,具有两个值,可由.NET的
if
s、
s、
for
s等理解。您可以像这样检查真实值:

public void function main()
{
    bool result = SqlCheck('martin', 'changeme');

    if (result == true) {
        // result was true
    } else {
        // result was false
    }
}

bool
变量的默认值为
false
。这仅适用于类/结构变量:本地变量需要显式初始化。

在主方法中,可以执行以下操作:

if (SqlCheck(string username, string password) ) {
    // This will be executed only if the method returned true
}
但是您的方法目前只返回true,我相信您将在这里执行其他操作来验证sql检查是否正确

bool sqlCheck = SqlCheck("username", "password");

if(sqlCheck) // ie it is true
{
    // do something
}

这里user和root是要检查的实际字符串

bool myCheck = SqlCheck("user", "root");

另一件在这里也很好的事情(IMO)是使方法名更具描述性。您可能不是将来阅读代码的唯一用户,而且
if(SqlCheck(username,password))
对阅读您代码的人没有任何帮助。可能类似于,
AreSqlCredentialsValid
或类似的东西。
bool myCheck = SqlCheck(myUser, myPassword);
bool myCheck = SqlCheck("user", "root");
if (myCheck) {
    // succeeded
} else {
    //failed
}