开发者

How can I eliminate code repetition while setting control visibility?

I have 4 text boxes ,i write 4 functions ,in each function i want one textbox to be visible true others false.

function1()
{
    Txtbox1.visible=true;
    Txtbox2.visble=false;
    Txtbox3.visible=false;
    TxtBox4.visible=false;
}

similarly i write 3 more function to make other text boxes visibility to true.How to do code optimization c#,Asp.net开发者_如何学运维


Set up an TextBox array. Such as

TextBox[] textboxes = { TxtBox1, TxtBox2, TxtBox3, TxtBox4 }; 

Then you can write a function to set visibility by index.

void SetVisibility(int index)
{
    // do index validation 

    textboxes[index].Visible = true;
    for (int i = 0; i < textboxes.Length; i++)
    {
        if (i != index) textboxes[i].Visible = false;
    }
}

So now instead of calling function1(), function()2, // etc., you would call SetVisibility(0), SetVisibility(1).


Write one function that sets all 4 controls visible to false, then sets the desired control (passed as a parameter) to true:

private void ShowTextBox(TextBox target)
{
    Txtbox1.Visible = false;
    Txtbox2.Visible = false;
    Txtbox3.Visible = false;
    Txtbox4.Visible = false;
    target.Visible = true;
}

Then call the function passing in the textbox instance you want to be visible:

ShowTextBox(Txtbox1);


Similar to the others, you could also use LINQ to do this a couple of different ways.

TextBox[] allTextBoxes = { TxtBox1, TxtBox2, TxtBox3, TxtBox4 };

void SetVisibility(TextBox visibleTextBox)
{
    allTextBoxes.Except(new TextBox[] { visibleTextBox })
                .ToList()
                .ForEach(t => t.Visible = false);

    visibleTextBox.Visible = true;
}

Usage:

SetVisibility(Txtbox1);

You could also do it so that you can set multiple (or none, so all are hidden) visible simultaneously (there are still even more ways to do this):

void SetVisibility1(params TextBox[] visibleTextBoxes)
{
    var visibleList = visibleTextBoxes.ToList();

    foreach (TextBox t in allTextBoxes)
    {
        t.Visible = visibleList.Contains(t);
    }
}

void SetVisibility2(params TextBox[] visibleTextBoxes)
{
    allTextBoxes.Except(visibleTextBoxes).ToList().ForEach(t => t.Visible = false);
    visibleTextBoxes.ToList().ForEach(t => t.Visible = true);
}

void SetVisibility3(params TextBox[] visibleTextBoxes)
{
    var visibleList = visibleTextBoxes.ToList();
    allTextBoxes.ToList().ForEach(t => t.Visible = visibleList.Contains(t));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜