错误不是所有代码路径 return 一个值?

Error not all code paths return a value?

我有以下功能,但出现以下错误:并非所有代码路径 returns 值。

public Int64 id(string fd, string tb)
{
    if (con.State == ConnectionState.Open)
    {
        con.Close();
    else
    {
        con.Open();
    }

    SqlCommand cmd = new SqlCommand("SELECT MAX (" + fd + ") FROM " + tb + "", con);
    cmd.CommandType = CommandType.Text;
    if (con.State == ConnectionState.Closed)
    {
        con.Open();
        Int64 I = Convert.ToInt64((cmd.ExecuteScalar().Equals(DBNull.Value) ? 0 : cmd.ExecuteScalar())) + 10;
        return I;
    }                
}

请帮助我理解为什么会发生这种情况以及如何纠正它。

这里的问题很简单。仅当条件 "con.State == ConnectionState.Closed" 为真时,您才 return 一个值。否则没有 return 值,这是编译器告诉你的。

public Int64 id(string fd, string tb)
{
    Int64 I = 0;

    if (con.State == ConnectionState.Open)
    {
        con.Close();
    else
    {
        con.Open();
    }

    SqlCommand cmd = new SqlCommand("SELECT MAX (" + fd + ") FROM " + tb + "", con);
    cmd.CommandType = CommandType.Text;
    if (con.State == ConnectionState.Closed)
    {
        con.Open();
        I = Convert.ToInt64((cmd.ExecuteScalar().Equals(DBNull.Value) ? 0 : cmd.ExecuteScalar())) + 10;
    }
    return I; 
}

return I 语句在 if (con.State == ConnectionState.Closed) 堵塞。这意味着它不会被称为它 con.State 没有关闭并且函数不会 returned 任何东西。 I 在函数的顶部被初始化为 0,因此如果 SQL 查询不是 运行.

,这将被 returned