2012-02-23 13 views
5

Nella classe BLL, ho scritto:Come usare System.Action con tipo restituito?

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

Nel BLL classe base, Ho un metodo:

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

Come posso usare TryAction() metodo con tipo di ritorno generica? si prega di avere un suggerimento.

risposta

7

È necessario utilizzare Func per rappresentare un metodo che restituirà un valore.

Di seguito è riportato un esempio

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

Grazie aiutato molto. – Pravin

6

Action è un delegato che ha un tipo di reso void, quindi se si desidera che restituisca un valore, non è possibile.

Per questo, è necessario utilizzare un delegato Func (ce ne sono molti - l'ultimo parametro di tipo è il tipo restituito).


Se si vuole semplicemente avere TryAction ritorno un tipo generico, farne un metodo generico:

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

return default(T); 
} 

A seconda di cosa esattamente si sta cercando di fare, potrebbe essere necessario utilizzare sia un metodo generico e Func delegato:

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

return default(T); 
} 
0

Si dovrebbe prendere in considerazione di utilizzare 01 Delegatoanziché delegato.

Problemi correlati