c# - 灵活的方法参数?

标签 c# sql

我有一个使用以下方法的类。

public cIPLink(int paramCaseNo, int paramIPID, string paramIPReference, int paramContactID)
    {            
        this.cLinkDate = DateTime.Now;
        this.cCaseNo = paramCaseNo;
        this.cIPID = paramIPID;
        this.cIPReference = paramIPReference;
        this.cContactID = paramContactID;

        string strConnect = BuildConnectionString();
        SqlConnection linkToDB = new SqlConnection(strConnect);
        linkToDB.Open();

        string sqlStat = "INSERT INTO tblIPLinks (LinkID, LinkDate, CaseNo, IPID, ContactID, IPReference)" +
                         "VALUES (@LinkID, @LinkDate, @CaseNo, @IPID, @ContactID, @IPReference);";
        SqlCommand sqlCom = new SqlCommand(sqlStat, linkToDB);

        sqlCom.Parameters.Add("@LinkID", SqlDbType.Int);
        sqlCom.Parameters.Add("@LinkDate", SqlDbType.Date);
        sqlCom.Parameters.Add("@CaseNo", SqlDbType.Int);
        sqlCom.Parameters.Add("@IPID", SqlDbType.Int);
        sqlCom.Parameters.Add("@ContactID", SqlDbType.Int);
        sqlCom.Parameters.Add("@IPReference", SqlDbType.Text);

        this.cLinkID = NextLinkID();

        sqlCom.Parameters["@LinkID"].Value = this.cLinkID;
        sqlCom.Parameters["@LinkDate"].Value = this.cLinkDate;
        sqlCom.Parameters["@CaseNo"].Value = this.cCaseNo;
        sqlCom.Parameters["@IPID"].Value = this.cIPID;
        sqlCom.Parameters["@ContactID"].Value = this.cContactID;
        sqlCom.Parameters["@IPReference"].Value = this.cIPReference;

        sqlCom.ExecuteNonQuery();

        linkToDB.Close();
    }

但是我想让它更加灵活一点。有时当调用该方法时我想删除字段IPID,有时我想删除字段ContactID。现在我考虑复制并粘贴这段代码并使用三个重载方法;一个仅包含 IPID,一个仅包含 ContactID,第三个包含两个字段,但我确信一定有一种更简洁的方法来完成我想要的操作。

有什么想法吗?

最佳答案

如果您使用 dotnet 4.0 及更高版本,则可以使用可选参数。

public cIPLink(int paramCaseNo, int paramIPID = -1, 
    string paramIPReference = null, int paramContactID = -1)

因此,从那一刻起,您可以按如下方式调用它:

cIPLink( paramCaseNo );
cIPLink( paramCaseNo, paramContactID:5 );

关于c# - 灵活的方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8836599/

相关文章:

c# - 为什么需要发出 IL 代码?

c# - WindowsImpersonationContext 下的程序集绑定(bind)。如何防止 FileLoadException?

C# : FieldInfo. GetValue 返回 null

mysql - 如何根据先前和最后更改的值构建新的日期列?

mysql - 一对一的关系

sql - 分配组 ID

c# - 迁移 "Legacy"SQLite 数据库以使用 Entity Framework 时的主键问题

c# - Swashbuckle/Swagger 没有从配置中获取路由

mysql - 如何使 MySQL 中的一行与另一行相对应?

mysql查询返回错误结果