使用委托、匿名(lambda)函数和函数指针

本文关键字:函数 lambda 指针 匿名 | 更新日期: 2023-09-27 18:27:10

我读过一些关于匿名(lambda)函数和委托的文章。我相信我正在处理一种情况,我的职能部门可以/应该利用它们。我不确定我的假设是否正确。

当前代码:

fDoSave(fGetSqlCheckEmpJob(), fGetSqlUpdateEmpJob(), fGetSqlInsertEmpJob());
fDoSave(fGetSqlCheckEmpPayrl(), fGetSqlUpdateEmpPayrl(), fGetSqlInsertEmpPayrl());
fDoSave(fGetSqlCheckEEO(), fGetSqlUpdateEEO(), fGetSqlInsertEEO());
fDoSave(fGetSqlCheckEmpPhone(), fGetSqlUpdateEmpPhone(), fGetSqlInsertEmpPhone());

fGetSqlCheck...()-以字符串形式返回sql语句,该字符串返回具有特定ID的所有行的count()fGetSqlUpdate...()以执行更新的字符串形式返回一条sql语句。fGetSqlInsert...()将sql语句作为执行插入的字符串返回。fDoSave()根据fGetCheck...() 返回的值进行更新或插入

fGetSql函数如下所示:

private string fGetSql...()
{
   StringBuilder sb = new StringBuilder();
   //Create sql statement
   return sb.ToString();
}

fDoSave函数如下所示:

private void fDoSave(string sSql_Check, string sSql_Update, sSql_Insert)
{
   OracleDataReader dr = ERPDB.sqlGetDataReader(sSql_Check);
   while (dr.Read())
   {
        if(fCheckIfRecrodExists(dr) > 0) //if fGetSqlCheck...() found a row with a specific ID
            //do update using sSql_Update
        else
            //do insert using sSql_Insert
    }
}

这可以使用lambda函数或委托重写吗?应该重写吗?应该如何重写?

使用委托、匿名(lambda)函数和函数指针

你的问题仍然很模糊,但我会这样说。

案例:

1:可重复使用且"静态"
如果重用SQL语句,并且它们有些静态,请将它们放在Properties中。并且考虑更好的名字。

2:可重复使用但"可变",尽管很简单
如果您重用SQL语句,并且它们是可变的,但不占用太多CPU,这意味着它们会根据不同的状态进行更改,并且创建和构建速度非常快,那么就让它们保持原样吧。

3:可重复使用但"可变"且复杂
如果您重用SQL语句,并且它们是可变的,但非常复杂,需要大量的CPU能力,请将它们放在方法中,但将它们作为委托调用,不要使它们匿名。

4:不可重复使用,但"可变"且复杂
如果您永远不会重用SQL语句(可能从来都不是这样),并且它们是可变的、非常复杂的,并且需要大量的CPU能力,请将它们放在一个匿名函数中。

在任何情况下
使用更好的名称。

我的建议
我更喜欢情况1和2,因为剩下的似乎是一个过于复杂的解决方案,解决了一个可能不存在的问题
此外,我不知道你的整个代码库,但我不喜欢应该保存的对象没有给fDoSave()。

我会这样做的:

// Also often called Upsert short for "Update or Insert"
public int Save(EmpObj employeeObj) 
{
     if(CheckIfEmployeeExists(employeeObj))
     {
         return Update(employeeObj); // returns rows affected
     }
     else
     {
         return Insert(employeeObj); // Returns new Id of the employee.
     }
}
// Other methods, where the select, update and insert statements lies 
or gets called    and build
public bool CheckIfEmployeeExists(employeeObj) // Check If Employee Exists
public int Update(employeeObj); // Updates the employee
public int Insert(employeeObj); // Inserts the employee