更好的解决gui代码?

时间:2012-03-22 04:13:26

标签: c# radio-button panel checkbox

只需学习C#,radiobuttons和复选框。没有紧迫感。 该代码用于显示已检查控件的名称,但它似乎不是一个优雅的解决方案。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TVC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "you clicked" + compute();
        }


        string compute()
        {
            string result = "";
            object o=label1;

            while (((Control)o).TabIndex!=7)
            {
                if ((o is RadioButton)||(o is CheckBox))
                {

                    if ((o is RadioButton)&&((RadioButton)o).Checked)

                    result += " "+((RadioButton)o).Text;

                    if ((o is CheckBox)&&((CheckBox)o).Checked)

                    result += " "+((CheckBox)o).Text;

                }

                o = GetNextControl((Control)o, true);
            }



            return result;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

checboxes和radiobuttons tabindexes从1到6计数,标签为0,按钮为7,以便GetNextControl工作。有没有更好的代码可以使用?enter image description here

2 个答案:

答案 0 :(得分:1)

我刚刚对此进行了测试并验证了它的工作原理。它使用递归和较新的dynamic关键字,因为RadioButtonCheckBoxButtonBase继承而没有Checked属性,否则你可以归结为那。动态允许我避免这种情况,因为我已经知道控件类型。

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = compute(this.Controls);
    }
    private string compute(Control.ControlCollection controls)
    {
        string result = String.Empty;
        foreach (Control control in controls)
        {
            if (control.Controls != null)
                result += compute(control.Controls);
            if (control is RadioButton || control is CheckBox)
            {
                dynamic checkControl = control;
                if (checkControl.Checked)
                {
                    result += checkControl.Text + ";";
                }
            }
        }
        return result;
    }

答案 1 :(得分:1)

如果您发现自己使用isas关键字来控制分支,那么您很可能不会利用polymorphism

如果您希望控件可以根据程序中的逻辑显示自己的状态,则一种更简洁的方法是将每个控件子类化并覆盖ToString()

在控件中放置用于创建文本表示的逻辑,而不是在使用多个控件的代码中(如果添加10个新控件类型,分支逻辑会有多复杂?)

最后,我会使用foreach而不是带有硬编码的while来迭代控件。

相关问题