2012-02-23 44 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委託而不是操作委託。