asp.net将方法名称作为参数传递给另一个方法

时间:2013-11-26 14:26:38

标签: c# asp.net

我试图在这个例子中找到如何使用委托的答案,但我仍然不知道如何将它用于我的代码冗余。我有这个代码,在我的应用程序中为每个dbAction重复:

public bool someDBMethod(params)
{
logDTO ldto = new logDTO("some text");
try
{
  if (DALmethod(params)) //DB operation is successfull
  {
    Log.insertLog(ldto); //inserrt log to DB
    return true;
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));
    throw new Exception (ex.Message);
  }
 catch (Exception ex)
 {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));
    throw new Exception (ex.Message);
 }

}

对于除行

之外的其他数据库操作,此代码相同
logDTO ldto = new logDTO("some text");

if (DALmethod(params)) //DB operation is successfull

我在其中创建DAL特定日志并调用DAL方法以插入/更新/删除数据库。这些DAL方法的参数不一样,但我可以使用一些包装器。

我想要求任何DAL方法

result = someDBMethod(DALmethod m, params p, logDTO l)

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

你可以传递一个Func<>作为你方法的论据。

public bool someDBMethod(Func<bool> callDalMethod, string message)
{
logDTO ldto = new logDTO(message);
try
{
  if (callDallMethod()) //DB operation is successfull
  {
    Log.insertLog(ldto); //inserrt log to DB
    return true;
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));
    throw new Exception (ex.Message);
  }
 catch (Exception ex)
 {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));
    throw new Exception (ex.Message);
 }

调用此方法:

  

someDBMethod(()=&gt; myDbMethod(param1,param 2),“message text”);

相关问题