我有很多重复的代码,我正试图摆脱它们,但我遇到了一些问题。
这是主要的:
我有几个计时器,都用数字标识,都有一个按钮来触发它们,但它使相同的代码无缘无故地一遍又一遍地重复,例如:
private void buttonTimer1_Start_Click(object sender, EventArgs e)
{
if (radioButtonTimer1_CountDown.Checked)
{
等等……
我已经能够为按钮创建一个事件并通过以下方式获取按钮的编号:
Button button = sender as Button;
var buttonName = button.Name;
var resultString = Regex.Match(buttonName, @"\d+").Value;
var buttonID = Int32.Parse(resultString);
所以如果可能的话,我想做的是使用类似的东西:
if ("radioButtonTimer"+buttonID+"_CountDown".Checked)
但是不可能从字符串访问属性“.Checked”。
处理该问题的最佳方法是什么?我有很多文本字段、单选按钮和我不需要的东西,以这种方式“动态”。
非常感谢您的时间和帮助。
最佳答案
使用 Controls.Find() 方法。
这可能是这样的:
Control[] ArrControls = this.Controls.Find("radioButtonTimer"+buttonID+"_CountDown");
if(ArrControls.Where(c => (c as RadioButton).Checked).ToList().Count > 0)
{
// Checked Radio Buttons
}
else
{
}
关于C# - 使用字符串命名单选按钮并访问其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978653/