2017-01-16 36 views
0

我該如何創建一個更通用的方法?如何使方法的開始和結束可重用?

我有一個方法:

 public ServiceAppointment UpdateService(Guid serviceGuid, Guid serviceActivityGuid) 
     { 
//this is repeated in 20 methods 
      var serviceAppointment = organizationService.Retrieve(
       "serviceappointment", 
       serviceActivityGuid, 
       new ColumnSet(true)); 
//end 
//Only the section here will vary 
      serviceAppointment["serviceid"] = new EntityReference("service", serviceGuid); 
//End 

//this is repeated in 20 methods 
      organizationService.Update(serviceAppointment); 

      return GetServiceActivity(serviceActivityGuid); 
//end 
     } 

正如你可以從上面看到的,只有這部分將來自法改爲方法:

serviceAppointment["serviceid"] = new EntityReference("service", serviceGuid); 

是否有可能創建一個方法將運行上面的方法的開始和結束並接受作爲參數的行更改?

+0

將代碼中的一個方法,並在另一端開始,並調用這些方法需要的時候。 –

+1

@Roma這在這裏不行。這兩種方法的狀態僅在這兩個代碼片段之間共享,並且它們高度耦合;他們需要始終一起調用,在他們之間發生特定的操作,而不是分開。它們並不是真正的獨立工作方式。 – Servy

回答

4

您可以使用委託注入的區別:

public ServiceAppointment UpdateService(Guid serviceGuid, Guid serviceActivityGuid, Action<Entity> action) 
{ 
    var serviceAppointment = organizationService.Retrieve(
      "serviceappointment", 
      serviceActivityGuid, 
      new ColumnSet(true)); 

    action(serviceAppointment); 

    organizationService.Update(serviceAppointment); 

    return GetServiceActivity(serviceActivityGuid); 
} 

調用,這將是:在

UpdateService(serviceGuid, serviceActivityGuid, 
    e => e["serviceid"] = new EntityReference("service", serviceGuid)); 
+0

https://drive.google.com/uc?id=0B47fuJY78GQhcmhQSUpIXzFCUDQ –

+0

我無法從您的代碼中確定OrganizationService.Retrieve返回的內容(由於變量命名,我錯誤地假定了ServiceAppointment)。接受OrganizationService.Retrieve(Entity?)返回的任何類型,並將操作參數更改爲該操作參數(例如,操作操作)。 – Eric

1

委託人是如何讓方法接受代碼作爲參數執行的。在你的情況下,你需要一個方法,接受serviceAppointment作爲參數,並提供沒有輸出,因爲方法​​應該接受,這是一個Action<ServiceAppointment>。然後調用者可以提供一個(可能是匿名的)方法,只需設置該服務約定的適當值即可。

+0

你能告訴我我將如何創建匿名方法來傳遞? –

+0

@MeggieLuski您可以[在文檔中查找](https://msdn.microsoft.com/en-us/library/bb882516.aspx)。 – Servy