所以我有这个函数,我在所有if-else
中都有一个返回但仍然收到编译错误:
并非所有代码路径都返回值
public async Task<bool> DeletePost(string update_id, string authId)
{
if (Utility.NetworkStatus.HasInternetAccess)
{
await APIs.DeletePost.DeletePostAPI(update_id, authId).ContinueWith((t) =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (t.Result != null)
{
return t.Result.status == 200;
}
else
{
return false;
//empty result, API failed
//not implemented
}
}
else
{
return false;
//task failed
//not implemented
}
});
}
else
{
return false;
//no network
//not implemented
}
}
谁能告诉我我做错了什么?
答案 0 :(得分:2)
是。您不会返回DeletePostAPI
public async Task<bool> DeletePost(string update_id, string authId)
{
if (Utility.NetworkStatus.HasInternetAccess)
{
return await APIs.DeletePost.DeletePostAPI(update_id, authId).ContinueWith((t) =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (t.Result != null)
{
return t.Result.status == 200;
}
else
{
return false;
//empty result, API failed
//not implemented
}
}
else
{
return false;
//task failed
//not implemented
}
});
}
else
{
return false;
//no network
//not implemented
}
}
答案 1 :(得分:1)
如果您完全删除ContinueWith
并使用更现代的await
代替您的代码变得更加简单:
public async Task<bool> DeletePost(string update_id, string authId)
{
if (Utility.NetworkStatus.HasInternetAccess)
{
try
{
var result = await APIs.DeletePost.DeletePostAPI(update_id, authId);
if (result != null)
{
return result.status == 200;
}
else
{
return false;
//empty result, API failed
//not implemented
}
}
catch
{
return false;
//task failed
//not implemented
}
}
else
{
return false;
//no network
//not implemented
}
}
答案 2 :(得分:0)
您需要返回等待的返回值。所以:
bool result = await APIs.DeletePost.DeletePostAPI(update_id, authId).ContinueWith((t) =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (t.Result != null)
{
return t.Result.status == 200;
}
else
{
return false;
//empty result, API failed
//not implemented
}
}
else
{
return false;
//task failed
//not implemented
}
});
return result;