为什么我得到“方法没有重载需要两个参数”

本文关键字:参数 两个 重载 方法 为什么 | 更新日期: 2023-09-27 18:32:55

我在一个DLL中有一个方法:

public static DataSet ExecuteDataset(string strcommandText,CommandType commandType,SqlParameter[] p)
 {
   CreateConnection();
   da = new SqlDataAdapter(strcommandText, con);
   da.SelectCommand.CommandType = commandType;
   da.SelectCommand.Parameters.AddRange(p);
   ds = new DataSet();
   da.Fill(ds);
   return ds;
 }    

我在另一个 DLL 中编写了一个方法:

   public static DataSet GetDeptDetails()
    {
    string strcommandText = "sp_DeptDetails";
    return SqlHelper.ExecuteDataset(strcommandText,CommandType.StoredProcedure);
     }

在这里,我收到此错误:

方法没有重载需要两个参数。

我做错了什么?

为什么我得到“方法没有重载需要两个参数”

public static DataSet ExecuteDataset(string strcommandText,CommandType commandType,SqlParameter[] p=null)
 {
   CreateConnection();
   da = new SqlDataAdapter(strcommandText, con);
   da.SelectCommand.CommandType = commandType;
   if(p!=null)
   {
     da.SelectCommand.Parameters.AddRange(p);
   }
   ds = new DataSet();
   da.Fill(ds);
   return ds;
 } 


public static DataSet GetDeptDetails()
    {
    string strcommandText = "sp_DeptDetails";
    return SqlHelper.ExecuteDataset(strcommandText,CommandType.StoredProcedure);
     } 

你期待 3 个参数

`public static DataSet ExecuteDataset(string strcommandText,CommandType commandType,SqlParameter[] p)`
 method.

但是调用此方法时只发送两个参数

return SqlHelper.ExecuteDataset(strcommandText,CommandType.StoredProcedure);

因此,当您通过仅传递两个参数来调用同一方法时,对象Sqlhelper寻找另一个具有两个参数的同名方法,从而导致此错误。

您可以通过传递第三个参数来解决问题,或者默认情况下只需将第三个参数设置为 null。

感谢您的回复。在上面的程序中,我们可以在 ExecuteDataset 方法参数中给出 sqlhelper 类作为可选参数,或者我们可以给出作为默认参数。因此,sqlparamter 传递不是其他方法的强制性要求,我们只能在需要时传递。