1

我在下面返回了一个昵称,但 Visual Studio 不断给我错误:并非所有代码路径都返回一个值。

我究竟做错了什么?我正在返回一个昵称......谁能进一步帮助我?虽然在谷歌上找不到解决方案...

    public string GetEigenaarBlog(int gebruikerid)
    {
        try
        {
            connection.Open();
            string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
            command = new OracleCommand(sql, connection);
            command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
            string nickname = Convert.ToString(command.ExecuteReader());
            return nickname;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
4

3 回答 3

3

在异常处理位中,没有返回任何内容。这是一个修复。

public string GetEigenaarBlog(int gebruikerid)
{
    try
    {
        connection.Open();
        string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
        command = new OracleCommand(sql, connection);
        command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
        string nickname = Convert.ToString(command.ExecuteReader());
        return nickname;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null; 
        //if you want to let the code know too put "throw;" here instead.
    }
    finally
    {
        connection.Close();
    }
}
于 2013-06-16T09:51:00.133 回答
0

尝试使用这个:

 public string GetEigenaarBlog(int gebruikerid)
            {
          string nickname = null;
                try
                {
                    connection.Open();
                    string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
                    command = new OracleCommand(sql, connection);
                    command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
                    nickname = Convert.ToString(command.ExecuteReader());           
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    connection.Close();                   
                }
     return nickname;

            }
于 2013-06-16T09:52:09.807 回答
0

您已声明字符串类型的方法,但如果您将在以下行之一中获得异常:

connection.Open();
string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
string nickname = Convert.ToString(command.ExecuteReader());

你不会返回任何东西,因为你没有返回语句的地方会有跳转到 catch 子句。

最佳实践(IMO)是将 return 语句放在try..catch..finally块之外并在方法的开头声明返回的变量(并使用一些默认值对其进行初始化)

于 2013-06-16T09:58:28.590 回答