-2

我无法弄清楚为什么我不断收到编译错误:“并非所有代码路径都返回值”。我正在编写一个简单的类方法,如果帐户可用,则应该返回 true,如果帐户不可用或为空/空,则返回 false。该方法的代码如下:

public static bool AccountAvailable(int AccountId)
{
    try
    {            
        bool accountavailable;

        string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";

        //grab a connection to the database
        Database database = DatabaseFactory.CreateDatabase();

        //create an instance of the command
        DbCommand command = database.GetSqlStringCommand(queryTransaction);

        object dataobject = command.ExecuteScalar();

        if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) == 0)
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) > 0)
        {
            accountavailable = true;
        }

        else
        {
            accountavailable = true;
        }

        return accountavailable;
    }

    catch
    {

    }
}

对此的任何帮助或建议将不胜感激。谢谢!!

4

3 回答 3

2

如果在返回值之前在代码中引发异常,则控制将移至catch块。然后它到达方法的末尾而不返回任何内容。

在 catch 块内或之后返回一些东西。

于 2013-09-03T20:33:19.593 回答
1

在您的 catch 块中,添加一个返回:

catch (Exception ex)
{
    // your code
    return null;
}
于 2014-08-02T09:15:48.637 回答
0

建议尝试此代码

public static bool AccountAvailable(int AccountId)
{
    bool accountavailable = false;
    try
    {            

        string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";

        //grab a connection to the database
        Database database = DatabaseFactory.CreateDatabase();

        //create an instance of the command
        DbCommand command = database.GetSqlStringCommand(queryTransaction);

        object dataobject = command.ExecuteScalar();

        if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) == 0)
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) > 0)
        {
            accountavailable = true;
        }

        else
        {
            accountavailable = true;
        }

    }

    catch
    {

    }
    return accountavailable;
}
于 2013-09-03T20:34:43.097 回答