错误消息:并非所有代码路径都返回一个值

时间:2018-06-27 14:54:18

标签: c# xamarin.ios

我在代码的以下行中收到此错误消息:

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();
        }
    }

3 个答案:

答案 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;
}