2012-02-23 86 views
5

在BLL类,我已经写了:如何使用System.Action和返回类型?

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()方法与一般的返回类型? 请有一个建议。

回答

7

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

感谢帮助了很多。 – Pravin 2012-02-24 05:45:00

6

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

您应该考虑使用Func委托而不是操作委托。