如何将这4个功能合二为一?

Med*_*tor 0 c# factory-pattern c#-2.0

你可以使用枚举: enum StatusRouter { Stop = 0, Start, Resume, Suspect };

public bool StartSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Start();
    }
    return false;
}
public bool ResumeSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Resume();
    }
    return false;
}
public bool SuspendSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Suspend();
    }
    return false;
}
public bool StopSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Stop();
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

dri*_*iis 7

您可以传入一个lambda,用于定义要对每个元素执行的Action.

就像是:

public bool ChangeSelectedRouterState(Action<Router> action) 
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            action(m_listPlatforms[i]);
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

像这样打电话:

ChangeSelectedRouterState(r => r.Stop());
Run Code Online (Sandbox Code Playgroud)

您将需要替换Router我为您的答案发明的类型,以替换您正在处理的特定类型.