2012-01-11 66 views
2

請看下面的代碼,其中一個客戶端訪問WCF服務泛型程序,從客戶端訪問WCF服務

功能GetPriority

public List<Priority> GetPriority() 
     { 
      List<Priority> lstPriority = new List<Priority>(); 

      using (TmsServiceClient client = new TmsServiceClient()) 
      { 
       try 
       { 
        lstPriority = client.GetPriority(); 
       } 
       catch (FaultException<TMSCustomException> myFault) 
       { 
        Console.WriteLine(myFault.Detail.ExceptionMessage); 
        client.Abort(); 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex.Message); 
        client.Abort();     
       } 
      } 
      return lstPriority; 
     } 

功能的getStatus:

public List<Status> GetStatus() 
    { 
     List<Status> lstStatus = new List<Status>(); 
     using (TmsServiceClient client = new TmsServiceClient()) 
     { 
      try 
      { 
       lstStatus = client.GetStatus(); 
      } 
      catch (FaultException<TMSCustomException> myFault) 
      { 
       Console.WriteLine(myFault.Detail.ExceptionMessage); 
       client.Abort();     
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
       client.Abort();     
      } 
     } 

     return lstStatus; 
    } 

這兩種方法都工作正常。可以看出,這兩種方法之間有許多相似之處,它們僅在方法調用和返回類型時纔有所不同。這可以使通用?如果是這樣怎麼辦?或者任何其他更好的方式,以便捕獲異常塊代碼不應該每次重複。

在此先感謝

回答

2

您可以輕鬆地重構幾乎整個Get ...方法爲普通之一。唯一真正的可變部分是調用哪個客戶端方法,可以使用Func<T,TResult>輕鬆解決。

private List<T> Get<T>(Func<TmsServiceClient, List<T>> clientCall) 
{ 
    List<T> results = new List<T>(); 
    using (TmsServiceClient client = new TmsServiceClient()) 
    { 
     try 
     { 
      // invoke client method passed as method parameter 
      results = clientCall(client); 
     } 
     catch (FaultException<TMSCustomException> myFault) 
     { 
      Console.WriteLine(myFault.Detail.ExceptionMessage); 
      client.Abort();     
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      client.Abort();     
     } 
    } 

    return results; 
} 

現在你的方法實現這個樣子:

public List<Status> GetStatus() 
{ 
    return Get<Status>(client => client.GetStatus()); 
} 

public List<Priority> GetPriority() 
{ 
    return Get<Priority>(client => client.GetPriority()); 
} 

編輯迴應OP評論

Func<TmsServiceClient, List<T>>作爲參數傳遞給Get<T>方法是delegate。委託是一種函數指針 - 一個對象,用於代理稍後要執行的一些動作(因此名稱)。

Func<TmsServiceClient, List<T>>基本上是一個代表,它接受一個輸入參數(的TmsServiceClient類型)並返回List<T>作爲結果。

現在,我們在做什麼例如GetStatus?我們創造這樣的委託實例(通過lambda expression) - 我們「告訴」它來執行GetStatus()方法上Client對象,我們將提供

// this line works the same as in example above 
    //     Take client as parameter call its .GetStatus method 
    return Get<Status>((TmsServiceClient client) => client.GetStatus()); 

而這正是發生在

// invoke client method passed as method parameter 
    results = clientCall(client); 

一行。代表執行我們要求的方法。

+0

我無法理解部分Func user1025901 2012-01-12 07:36:29

+0

@ user1025901:'Func >'是一個代表 - 請檢查我的編輯。 – 2012-01-12 20:02:01

相關問題