如何在没有复制/粘贴代码块的情况下重用逻辑-C#

时间:2019-03-18 14:21:52

标签: c#

我的项目多次更改了下面的代码,仅更改了几个变量。我注意到了随着例如***值***。

client-max-body-size: "200m"

如何在不多次复制和粘贴if语句的情况下使用具有不同值的相同逻辑?

1 个答案:

答案 0 :(得分:2)

对我来说,您想要类似的声音

private void foo(string matchText, string sortBy) {
    if (comboBox1.Text == matchText)
    {
        string dgvconn = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
        string sql = "select * from Records where UserID = @userID Order By " + sortBy;
        SqlConnection connection = new SqlConnection(dgvconn);
        SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
        dataadapter.SelectCommand.Parameters.AddWithValue("@userID", currentUserID);
        DataSet ds = new DataSet();
        connection.Open();
        dataadapter.Fill(ds, "Records");
        connection.Close();
        recordsDataGridView.DataSource = ds;
        recordsDataGridView.DataMember = "Records";
    }     
}//foo

//Call the method
foo("Most recent first", "Date DESC");
foo("Most recent last", "Date");
foo("By Username", "User");