-2

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

4

1 回答 1

3

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

案例:

1:可重用和“静态”
如果您重用 SQL 语句并且它们有些静态,请将它们放在属性中。并考虑更好的名字。

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
于 2013-08-09T23:40:38.983 回答