我在代码的以下行中收到此错误消息:
public async Task<bool> TestMakePurchase(string productId, string payload)
错误CS0161:“ Game1.TestMakePurchase(字符串,字符串)”:并非所有代码 路径返回值(CS0161)
此错误消息是什么意思,我的代码有什么问题?
完整代码:
async void CheckPurchase()
{
bool purchaseIsSuccessful = await TestMakePurchase("com.website.appName.purchaseName", "");
if (purchaseIsSuccessful)
{
}
else
{
}
}
public async Task<bool> TestMakePurchase(string productId, string payload)
{
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync();
if (!connected)
{
return false;
}
var purchase = await billing.PurchaseAsync(productId, ItemType.InAppPurchase, payload);
if (purchase == null)
{
return false;
}
else
{
return true;
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
}
finally
{
await billing.DisconnectAsync();
}
}
答案 0 :(得分:2)
如果第一个try
捕获到异常,则有可能绕过您所有的return
语句。您可以通过在方法末尾添加返回权来解决此问题:
public async Task<bool> TestMakePurchase(string productId, string payload)
{
var billing = CrossInAppBilling.Current;
try
{
// Snip
}
catch (InAppBillingPurchaseException purchaseEx)
{
}
finally
{
await billing.DisconnectAsync();
}
// Add this line
return false;
}
答案 1 :(得分:0)
如果try块中发生异常,则代码退出时将没有任何return
值。请在return
块之后添加finally
语句。
答案 2 :(得分:0)
您不必在每个条件语句上都调用return。只需使用变量( purchaseState )跟踪状态即可。目前尚不清楚引发 InAppBillingPurchaseException 时会发生什么情况。我至少会记录此错误。
public async Task<bool> TestMakePurchase(string productId, string payload)
{
var purchaseSuccesful = false;
var billing = CrossInAppBilling.Current;
try
{
if (await billing.ConnectAsync())
{
var purchase = await billing.PurchaseAsync(productId, ItemType.InAppPurchase, payload);
purchaseSuccesful = purchase != null;
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
//log this error?
}
finally
{
await billing.DisconnectAsync();
}
return purchaseSuccesful;
}