C#缩短重复的StreamReader

时间:2017-09-16 17:21:22

标签: c# winforms visual-studio-2017

以下代码读取.txt文件并读取以代码中声明的字符开头的某一行。

 private void rb_point1_CheckedChanged(object sender, EventArgs e)
    {

        string line;

        StreamReader file = new StreamReader(ccpath);
        while ((line = file.ReadLine()) != null)
        {
            if (line.StartsWith("point01:"))
            {
                message = (line.Split(':')[1]);
                txtb_message.Text = message;
            }
        }
    }
    private void rb_point2_CheckedChanged(object sender, EventArgs e)
    {

        string line;

        StreamReader file = new StreamReader(ccpath);
        while ((line = file.ReadLine()) != null)
        {
            if (line.StartsWith("point02:"))
            {
                message = (line.Split(':')[1]);
                txtb_message.Text = message;
            }
        }
    }
    private void rb_point3_CheckedChanged(object sender, EventArgs e)
    {

        string line;

        StreamReader file = new StreamReader(ccpath);
        while ((line = file.ReadLine()) != null)
        {
            if (line.StartsWith("point03:"))
            {
                message = (line.Split(':')[1]);
                txtb_message.Text = message;
            }
        }
    }
    private void rb_point4_CheckedChanged(object sender, EventArgs e)
    {

        string line;

        StreamReader file = new StreamReader(ccpath);
        while ((line = file.ReadLine()) != null)
        {
            if (line.StartsWith("point04:"))
            {
                message = (line.Split(':')[1]);
                txtb_message.Text = message;
            }
        }
    }
    private void rb_point5_CheckedChanged(object sender, EventArgs e)
    {

        string line;

        StreamReader file = new StreamReader(ccpath);
        while ((line = file.ReadLine()) != null)
        {
            if (line.StartsWith("point05:"))
            {
                message = (line.Split(':')[1]);
                txtb_message.Text = message;
            }
        }
    }

我遇到的问题是我有50个单选按钮,这意味着这个代码需要重复50次。我没有关于如何缩短它的想法,或者至少让眼睛看起来更容易

1 个答案:

答案 0 :(得分:1)

第一个改进是一种方法,可以做你想要的,并接受差异的参数。像这样:

private void rb_point1_CheckedChanged(object sender, EventArgs e)
{
    ReadLineAndDisplayText("point01:");
}

private void ReadLineAndDisplayText(string lineStart)
{
    string line;

    StreamReader file = new StreamReader(ccpath);
    while ((line = file.ReadLine()) != null)
    {
        if (line.StartsWith(lineStart))
        {
            message = (line.Split(':')[1]);
            txtb_message.Text = message;
        }
    }
}

就像你已经摆脱了大多数重复。

接下来是每个单选按钮没有新的rb_point1_CheckedChanged()方法,但为所有按钮分配相同的方法。然后,您可以使用sender来识别按下的单选按钮。在设计师中,您可以例如分配Tag,所以你的代码是这样的:

private void anyRadioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton radio = (RadioButton) sender;
    string lineStart = (string) radio.Tag;
    ReadLineAndDisplayText(lineStart);
}

就像那样,你最终只会使用2种方法。