【发布时间】:2016-03-18 10:40:54
【问题描述】:
我添加了一个bool 方法,它提供执行OAuth 身份验证并返回真或假。基于用户和密码检查的结果。
但我在 LoginService() 方法上遇到错误,说明:
'MongoDBApp.Services.AuthenticationService.LoginService(string, string)': not all code paths return a value
我用谷歌搜索了错误,结果显示它是因为错误说,该方法没有返回方法返回类型中定义的值。
我已经检查了该方法,它在每个条件下都返回 true 或 false。似乎布尔值没有在 LoginAsync() 内部方法之外返回。
有谁知道为什么该方法没有收到返回的布尔值?
这是LoginService(),返回类型为 bool:
private bool LoginService(string username, string password)
{
string ConnectionName = "Username-Password-Authentication";
auth0.LoginAsync(connection: ConnectionName, userName: username, password: password).ContinueWith(t =>
{
if (t.IsFaulted)
{
return false;
}
else
{
Messenger.Default.Send<UpdateLoginMessage>(new UpdateLoginMessage());
return true;
}
},
TaskScheduler.FromCurrentSynchronizationContext());
}
【问题讨论】:
-
为什么不在 if-else 块中分配布尔变量的值,并在
TaskScheduler.FromCurrentSynchronizationContext());之后返回它? -
TaskScheduler.FromCurrentSynchronizationContext() 返回什么?很久以前,我在编写汇编语言时被告知,调试具有公共返回点的程序会更容易。现在可能没那么必要了,但我不惜一切代价避免多次退货。正如一个非常好的答案所指出的那样,将两个 return 语句替换为对函数/方法范围返回变量的赋值。然后在函数/方法的末尾返回该值。
标签: c# boolean return boolean-logic