Asp.net

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

  • January 5, 2013

在 BLL 課上,我寫過:

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

在 BLL 基類中,我有一個方法:

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

如何使用TryAction()具有通用返回類型的方法?請給個建議。

您需要使用 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))
       }
   }

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);
}

根據您要執行的操作,您可能需要同時使用泛型方法和Func委託:

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

return default(T);
}

引用自:https://stackoverflow.com/questions/9414786