C#:如何减少以下代码

时间:2014-12-01 06:43:20

标签: c#

我想执行与现在正在执行的功能相同的过程,但我想要更紧凑的功能。

任何人都可以帮我减少这段代码......?

private void UpdateView(bool IsUpdateViewRequired)
{
        try
        {
            if (IsUpdateViewRequired == true)
            {
                this.Height = 210;
                labelStatus.Text = string.Empty;
                progressBar.Value = 0;
                buttonCancel.Visible = true;
                buttonStart.Visible = false;
            }
            else
            {
                this.Height = 165;
                buttonCancel.Visible = false;
                buttonStart.Visible = true;
            }
        }
        catch (Exception)
        {
            return;
        }
}

3 个答案:

答案 0 :(得分:6)

private void UpdateView(bool IsUpdateViewRequired)
{
    if (IsUpdateViewRequired) progressBar.Value = (labelStatus.Text = string.Empty).Length;
    this.Height = (buttonStart.Visible = !(buttonCancel.Visible = IsUpdateViewRequired)) ? 165 : 210;
}

享受简短;)抱歉,这是不可读的。

答案 1 :(得分:3)

你可以将代码减少到下面的代码(我不认为这会有任何区别,因为你的语句只是简单的命令)

private void UpdateView(bool IsUpdateViewRequired)
{

            if (IsUpdateViewRequired == true)
            {
                this.Height = 210;
                labelStatus.Text = string.Empty;
                progressBar.Value = 0;

            }
            else
            {
                this.Height = 165;
            }
            buttonCancel.Visible = IsUpdateViewRequired;
            buttonStart.Visible = !IsUpdateViewRequired;

}

答案 2 :(得分:2)

首先,您不需要try/catch。您也不需要== truethis.也是多余的。此外,你可以消除一些if声明:

 private void UpdateView(bool IsUpdateViewRequired)
 {
            Height =IsUpdateViewRequired? 210:165;
            buttonCancel.Visible = IsUpdateViewRequired;
            buttonStart.Visible = !IsUpdateViewRequired;
            if (IsUpdateViewRequired)
            {
               labelStatus.Text = string.Empty;
               progressBar.Value = 0;
            }            
}