C# 错误并非所有代码路径都返回值?

C# 错误并非所有代码路径都返回值?,c#,.net,vb.net,C#,.net,Vb.net,我有以下函数,但我得到以下错误:并非所有代码路径都返回值 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 " +

我有以下函数,但我得到以下错误:并非所有代码路径都返回值

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”为true时,才返回值。否则就没有返回值,这是编译器告诉您的

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

returni语句位于if(con.State==ConnectionState.Closed)块内。这意味着它不会被称为con.State,并且函数不会返回任何内容。在函数顶部初始化为0,如果SQL查询未运行,则返回。

请考虑删除不相关的代码,以显示从您的帖子中的SQL注入。还考虑阅读有关错误的MSDN文档(通过在VS中选择错误时单击F1或通过生成输出中显示的错误代码搜索)。如果没有帮助-请编辑您的帖子,以使用一致的indentation.Yup格式化代码。您的代码中确实存在该错误。你的问题是什么?事实上我只找到了一个写代码的地方,但我应该在哪里写问题,我是新向导mereturn我必须在括号外。事实上,在我尝试在catch中尝试catch并返回true之后,它在vs 2012 pro中工作,但在vs 2010中没有错误,thanx againI修复了一个没有初始化“i”的错误,改进了格式并添加了一些解释。但是,此代码仍然存在重大问题。仅当连接最初打开时,它才会运行SQL命令。它打开和关闭连接的原因我无法理解,它很容易受到SQL注入和变量名可能更好。。。