2012-02-23 20 views
5

, ben yazdım:System.Action nasıl kullanılır? BLL sınıfta

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

BLL temel sınıf içinde, bir yöntem vardır:

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

nasıl jenerik dönüş türü ile TryAction() yöntemi kullanabilirsiniz? lütfen bir öneriniz var.

cevap

7

Değeri döndürecek bir yöntemi temsil etmek için Func kullanmanız gerekir.

Aşağıda

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

sayesinde çok yardımcı bir örnektir. – Pravin

6

, void dönüş türüne sahip bir temsilci, dolayısıyla bir değer döndürmek isterseniz, yapamazsınız.

Bunun için, Func temsilcisini kullanmanız gerekir (çok fazla - son tip parametresi dönüş türüdür).


basitçe, TryAction dönüşü bir genel tür var jenerik yöntem haline yapmak isterseniz:


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

return default(T); 
} 
Yapmaya çalıştığınız tam olarak ne bağlı olarak, gerekebilir

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

return default(T); 
} 
0

Sen 01 kullanmaya düşünmelisiniz: genel bir yöntem ve Func temsilci ikisini de kullanmak Eylem delege yerinedelege.

İlgili konular