我有大约20个具有几乎相同模式的函数,我在Sites数组上运行,使用Site对象创建SiteOperation并执行一些操作(在这种情况下有一个param但有时没有或更多)
int wantedBandwidthInLBps = 2048 / 8;
foreach (Sites site in _sitesManagement.GetAll())
{
SiteOperation siteOperation = new SiteOperation(site);
siteOperation.LimitBandwidth(wantedBandwidthInLBps);
}
foreach (Sites site in _sitesManagement.GetAll())
{
SiteOperation siteOperation = new SiteOperation(site);
siteOperation.KillJames();
}
foreach (Sites site in _sitesManagement.GetAll())
{
SiteOperation siteOperation = new SiteOperation(site);
siteOperation.FlyToMoon(2012, new TaskIdentifier(10,20));
}
是否可以包装此代码,因此我将发送操作给_sitesManagement,它将在所有网站上运行此操作?
答案 0 :(得分:4)
试试这个:
void PerformOperationOnAllSites(Action<SiteOperation> doIt) {
foreach (Sites site in _sitesManagement.GetAll()) {
SiteOperation siteOperation = new SiteOperation(site);
doIt(siteOperation);
}
}
...
_sitesManagement.PerformOperationOnAllSites(op => op.LimitBandwidth(wantedBandwidthInLBps));
_sitesManagement.PerformOperationOnAllSites(op => op.KillJames());
_sitesManagement.PerformOperationOnAllSites(op => op.FlyToMoon(2012, new TaskIdentifier(10,20));
答案 1 :(得分:1)
public void DoSiteOperationActions(Action<SiteOperation> toDo)
{
foreach (Sites site in _sitesManagement.GetAll())
{
SiteOperation mySiteOperation = new SiteOperation(site);
toDo(mySiteOperation);
}
}
然后你可以把它称为......
DoSiteOperationActions(so => so.FlyToMoon(2012, new TaskIdentifier(10,20)));
语法可能有些偏差,我这里没有IDE,但这里有更多信息 http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
答案 2 :(得分:0)
这听起来像是模板方法模式的一个很好的候选者。
答案 3 :(得分:0)
private static void InvokeMethod(Action<SiteOperation> action)
{
foreach (SiteOperation siteOperation in _sitesManagement.GetAll()
.Select(site=>new SiteOperation(site))
{
action(siteOperation);
}
}
..
public static void KillJames()
{
InvokeMethod(so => so.KillJames());
}
public static void LimitBandwidth(int wantedBandwidthInLBps)
{
InvokeMethod(so => so.LimitBandwidth(wantedBandwidthInLBps));
}
public static void FlyToMoon(int year=2012, TaskIdentifier ti=new TaskIdentifier(10,20))
{
InvokeMethod(so => so.FlyToMoon(year, ti));
}