[英]How to make the beginning and the end of a method reusable?
我将如何创建更通用的方法?
我有一个方法:
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);
是否可以创建一个方法,该方法将运行上述方法的开头和结尾,并接受变化的行作为参数?
您可以使用委托来注入差异:
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));
委托是您如何让方法接受代码作为参数执行的方法。 在您的情况下,您需要一个方法,该方法接受serviceAppointment
作为参数,并且不提供UpdateService
应该接受的方法输出,即Action<ServiceAppointment>
。 然后,调用者可以提供一个(可能是匿名的)方法,该方法可以简单地设置该服务约会的适当值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.