【发布时间】: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