不返回值

本文关键字:返回值 | 更新日期: 2023-09-27 18:01:12

实际上,我的代码显示了一个错误"并非所有代码路径都返回值">

public DataTable Do_Insert_Update_Delete(string Proc_name, params object[] arg)
{
    if (Proc_name == "Vehicle_Booked_Info")
    {
        SqlCommand com = new SqlCommand("Vehicle_Booked_Info", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.Add(" @Today_Date", SqlDbType.DateTime).Value = Convert.ToDateTime(arg[0].ToString());
        SqlDataAdapter sda = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        return dt;
    }
}

甚至我把return dt 放在这里

如果我使用这个out of If子句,它显示的错误是

当前上下文中不存在dt

如何克服这一点?

不返回值

您正在返回if语句内部,编译器无法确定是否满足条件。您需要在if块之外或在else块中返回一些东西,因为您的方法假定返回类型为DataTable的对象,那么如果Proc_name不是"Vehicle_Booked_Info",那么您的方法将不会返回任何东西。所以改变你的方法,比如:

public DataTable Do_Insert_Update_Delete(string Proc_name, params object[] arg)
{
    if (Proc_name == "Vehicle_Booked_Info")
    {
        SqlCommand com = new SqlCommand("Vehicle_Booked_Info", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.Add(" @Today_Date", SqlDbType.DateTime).Value = Convert.ToDateTime(arg[0].ToString());
        SqlDataAdapter sda = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        return dt;
    }
  else
    { 
     return null; //Or some default value.
    }       
}
public DataTable Do_Insert_Update_Delete(string Proc_name, params object[] arg)
{
    DataTable dt = new DataTable();
    if (Proc_name == "Vehicle_Booked_Info")
    {
        SqlCommand com = new SqlCommand("Vehicle_Booked_Info", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.Add(" @Today_Date", SqlDbType.DateTime).Value =       Convert.ToDateTime(arg[0].ToString());
        SqlDataAdapter sda = new SqlDataAdapter(com);
        sda.Fill(dt);
    }       
        return dt;
}

在方法结束前添加return null;

    }       
    return null;
}

这里不需要else短语。

编译器显示错误,因为当不满足if语句条件时,方法不返回值。

这是一种糟糕的代码实践。。

将其更改为以下

public DataTable Do_Insert_Update_Delete(string Proc_name, params object[] arg)
{
    if (Proc_name == "Vehicle_Booked_Info")
    {
        SqlCommand com = new SqlCommand("Vehicle_Booked_Info", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.Add(" @Today_Date", SqlDbType.DateTime).Value = Convert.ToDateTime(arg[0].ToString());
        SqlDataAdapter sda = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        return dt;
    }       
    return new DataTable();// or return null

}