如何使用返回类型的System.Action?

Pra*_*vin 6 .net asp.net action c#-4.0

在BLL课程中,我写道:

Private List<T> GetData(string a, string b)
{
   TryAction(()=>{
      //Call BLL Method to retrieve the list of BO.
       return BLLInstance.GetAllList(a,b);
    });
}
Run Code Online (Sandbox Code Playgroud)

在BLL基类中,我有一个方法:

protected void TryAction(Action action)
{
 try
 {
   action();
 }
 catch(Exception e)
 {
   // write exception to output (Response.Write(str))
 }
}
Run Code Online (Sandbox Code Playgroud)

如何使用TryAction()泛型返回类型的方法?请有个建议.

Ram*_*esh 8

您需要使用Func来表示将返回值的方法.

以下是一个例子

    private List<int> GetData(string a, string b)
    {
        return TryAction(() =>
        {
            //Call BLL Method to retrieve the list of BO.
            return BLLInstance.GetAllList(a,b);
        });
    }


    protected TResult TryAction<TResult>(Func<TResult> action)
    {
        try
        {
            return action();
        }
        catch (Exception e)
        {
            throw;
            // write exception to output (Response.Write(str))
        }
    }
Run Code Online (Sandbox Code Playgroud)


Ode*_*ded 7

Action是一个具有void返回类型的委托,因此如果您希望它返回一个值,则不能.

为此,您需要使用Func委托(有很多 - 最后一个类型参数是返回类型).


如果您只想TryAction返回泛型类型,请将其转换为通用方法:

protected T TryAction<T>(Action action)
{
 try
 {
   action();
 }
 catch(Exception e)
 {
   // write exception to output (Response.Write(str))
 }

 return default(T);
}
Run Code Online (Sandbox Code Playgroud)

根据您要执行的操作,您可能需要同时使用泛型方法和Func委托:

protected T TryAction<T>(Func<T> action)
{
 try
 {
   return action();
 }
 catch(Exception e)
 {
   // write exception to output (Response.Write(str))
 }

 return default(T);
}
Run Code Online (Sandbox Code Playgroud)