c# - 如何将多个参数传递给一个方法?

标签 c# asp.net

C# - 我有一个方法需要 9 个参数(3 个是整数,6 个是字符串)。处理这个问题的最佳方法是什么?我应该如何在不指定这么多参数的情况下调用该方法。

方法看起来像这样

public void addProfileData(string profileText, string emailText, string serverText, int repeatText, int timeoutText, string urlText, string elementIDText, string textToBeVerifiedText, int benchmarkTime)
{
    int pid = -1;
    SqlCommand myCommand = new SqlCommand("AddProfileInformation", myConnection);
    myCommand.CommandType = CommandType.StoredProcedure;
    SqlParameter paramprofileText = new SqlParameter("@profileText", SqlDbType.NVarChar);
    paramprofileText.Value = profileText;
    myCommand.Parameters.Add(paramprofileText);

    SqlParameter paramemailText = new SqlParameter("@emailText", SqlDbType.NVarChar);
    paramemailText.Value = emailText;
    myCommand.Parameters.Add(paramemailText);

    myConnection.Open();
    using (SqlDataReader rdr = myCommand.ExecuteReader(CommandBehavior.CloseConnection))
    {
        while (rdr.Read())
        {
            pid = rdr.GetInt32(rdr.GetOrdinal("pid"));
        }
        rdr.Close();
    }
    myConnection.Close();
    if (pid != -1)
    {
        addPingData(serverText, repeatText, timeoutText, pid);
        addPLTData(urlText, elementIDText, textToBeVerifiedText, benchmarkTime, pid);
    }
}

最佳答案

为了使它看起来更整洁,将参数放入它自己的类中。

所以创建一个这样的类:

public class ProfileViewModel{
  public string ProfileText{get;set;};
  public string EmailText{get;set;};
  public string ServerText{get;set;};
  public int RepeatText{get;set;};
}

然后,将方法签名更改为:

public void addProfileData( ProfileViewModel model )

然后你可以像这样访问方法内部的所有参数

paramprofileText.Value = model.ProfileText;

关于c# - 如何将多个参数传递给一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5617401/

相关文章:

c# - 向按钮添加新事件

c# - ASP.NET Core 6 中租户特定的容器

c# - 逐字字符串缺少回车符

c# - 如何在 C#/.Net 中集成 MailChimp

c# - VCCodeModel 不在 VCCodeModel 命名空间中?

javascript - 在 Chrome 中设置输入文件文本颜色时出现问题

c# - 设备唯一 ID 和 Azure 移动服务

.net - 如何防止 Web 服务结果缓存在 ASP.NET Web 服务中?

asp.net - 获取 Controller asp.net-core 中的当前文化

c#.net 使用向导控件从动态框保持控件状态