如何从这个c#代码块中删除重复

时间:2017-04-21 08:06:38

标签: c#

我编写了这段代码,但在代码审核过程中,有人建议这是重复的代码,我需要从此代码中删除代码重复。任何人都可以建议我如何更好地使这些代码,以避免重复。

private void ShowHideEmailContents(string email, string email2, string format, string tooltip, bool isReadOnly)
{
    if (isReadOnly)
    {
        hlEmail.NavigateUrl = string.Format(format, email);
        hlEmail2.NavigateUrl = string.Format(format, email2);
        hlEmail.Text = email;
        hlEmail2.Text = email2;
        hlEmail.ToolTip = tooltip;
        hlEmail2.ToolTip = tooltip;
        hlEmail.Visible = isReadOnly;
        hlEmail2.Visible = isReadOnly;
        txtEmail.Visible = !isReadOnly;
        txtEmail2.Visible = !isReadOnly;
    }
    else
    {
        txtEmail.Text = email;
        txtEmail2.Text = email2;
    }
}

2 个答案:

答案 0 :(得分:7)

请注意,复制存在是因为您在两次上执行相同的操作,只是在不同的对象上。

要解决这个问题,请创建一个新方法,只执行一次

private static void ShowHideEmailContents(?? hl, ?? txt, string email, string format, string tooltip, bool isReadOnly)
{
    if (isReadOnly)
    {
        hl.NavigateUrl = string.Format(format, email);
        hl.Text = email;
        ...
    }
    else
    {
        txt.Text = email;
    }
}

调用它两次

private void ShowHideEmailContents(string email, string email2, string format, string tooltip, bool isReadOnly)
{
    ShowHideEmailContents(hlEmail, txtEmail, email, format, tooltip, isReadOnly);
    ShowHideEmailContents(hlEmail2, txtEmail2, email2, format, tooltip, isReadOnly);
}

答案 1 :(得分:0)

您可以通过封装逻辑来最小化传递的参数数量,以便在类中设置电子邮件对象的属性:

public sealed class EmailOptionsSetter
{
    readonly string _tooltip;
    readonly string _format;
    readonly bool   _isReadOnly;

    public EmailOptionsSetter(string tooltip, string format, bool isReadOnly)
    {
        _tooltip    = tooltip;
        _format     = format;
        _isReadOnly = isReadOnly;
    }

    public void SetOptions(YourEmailType emailObj, string email)
    {
        emailObj.NavigateUrl = string.Format(_format, email);
        emailObj.Text        = email;
        emailObj.ToolTip     = _tooltip;
        emailObj.Visible     = _isReadOnly;
    }
}

然后你可以这样称呼它:

    private void ShowHideEmailContents(string email, string email2, string format, string tooltip, bool isReadOnly)
    {
        if (isReadOnly)
        {
            var optionsSetter = new EmailOptionsSetter(tooltip, format, isReadOnly);
            optionsSetter.SetOptions(hlEmail, email);
            optionsSetter.SetOptions(hlEmail2, email2);

            txtEmail.Visible  = !isReadOnly;
            txtEmail2.Visible = !isReadOnly;            
        }
        else
        {
            txtEmail.Text  = email;
            txtEmail2.Text = email2;
        }
    }