我有三个单选按钮。他们更改事件背后的代码如下:
private void uxRajRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (uxRajRadioButton.Checked == true)
{
uxPersonBettingLabel.Text = "Raj";
GuySelected = 0;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
private void uxPaulRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (uxPaulRadioButton.Checked == true)
{
uxPersonBettingLabel.Text = "Paul";
GuySelected = 1;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
private void uxMikeRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (uxMikeRadioButton.Checked == true)
{
uxPersonBettingLabel.Text = "Mike";
GuySelected = 2;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
只有三个单选按钮这是可以接受的,但如果我说 7 个单选按钮,每个按钮在其更改事件后面有 20 行代码,那么这将是很多(不必要的?)代码。我试图缩短上述内容并最终得到以下内容。它是否正确?
private void uxRajRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode(this.uxRajRadioButton, 0);
}
private void uxPaulRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode(this.uxPaulRadioButton,1);
}
private void uxMikeRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode(this.uxMikeRadioButton, 2);
}
int GuySelected=0;
public void radioButtonCode(RadioButton myRadio, int mybettorIndex)
{
if (myRadio.Checked == true)
{
GuySelected = mybettorIndex;
uxPersonBettingLabel.Text = Guys[GuySelected].Name;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}