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

时间:2013-08-09 23:19:40

标签: c# lambda delegates anonymous-function

我已经阅读了一些关于匿名(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函数或委托重写它,应该吗?应该如何重写?

1 个答案:

答案 0 :(得分:3)

你的问题仍然含糊不清,但我会这样说。

例:

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