6

我有大约 20 个具有几乎相同模式的函数,我在站点数组上运行,使用站点对象创建 SiteOperation 并执行一些操作(在这种情况下只有一个参数,但有时没有或更多)

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 它将在所有站点上运行此操作?

4

4 回答 4

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));
于 2012-06-05T12:35:03.053 回答
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

于 2012-06-05T12:39:31.820 回答
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));
    }
于 2012-06-05T12:44:47.380 回答
0

这听起来像是模板方法模式的一个很好的候选者。

http://en.wikipedia.org/wiki/Template_method_pattern

于 2012-06-05T12:33:26.953 回答