【问题标题】:better solution to gui code?gui代码的更好解决方案?
【发布时间】:2012-04-06 15:56:07
【问题描述】:

刚刚学习 C#、单选按钮和复选框。没有紧迫感。 该代码用于显示选中控件的名称,但它似乎不是一个优雅的解决方案。

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)
        {

        }
    }
}

复选框和单选按钮标签索引从 1 到 6 计数,标签为 0,按钮为 7,以便 GetNextControl 起作用。有更好的代码吗?

【问题讨论】:

  • 无论做什么,都要避免使用幻数。即使这是您使用的最终代码,也将 7 提取到单独的常量中。
  • +1 关于幻数的好建议

标签: c# radio-button panel checkbox


【解决方案1】:

我刚刚对此进行了测试并验证了它是否有效。它使用递归和较新的dynamic 关键字,因为看起来RadioButtonCheckBox 继承自ButtonBase,它没有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;
    }

【讨论】:

    【解决方案2】:

    如果您发现自己使用 isas 关键字来控制分支,则很有可能您没有使用 polymorphism

    如果您想让控件根据程序中的逻辑显示自己的状态,一种更简洁的方法是对每个控件进行子类化并覆盖ToString()

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

    最后,我会使用 foreach 而不是带有硬编码数字的 while 来遍历控件。

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 2011-11-21
      • 1970-01-01
      相关资源
      最近更新 更多