我制作了一个简单的代码,接受(输入密钥)所选的单选按钮。并检查radiobutton文本是否与答案匹配。但是这个代码太冗余了,有没有办法让它更简单?
private void btn1_KeyDown(object sender, KeyEventArgs e)
{
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (btn1.Text == ans)
{
scoreAdd();
MessageBox.Show("Correct");
}
else
{
MessageBox.Show(ans);
}
currentRow++;
nextRow();
}
private void btn3_KeyDown(object sender, KeyEventArgs e)
{
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (btn3.Text == ans)
{
scoreAdd();
MessageBox.Show("Correct");
}
else
{
MessageBox.Show(ans);
}
currentRow++;
nextRow();
}
private void btn4_KeyDown(object sender, KeyEventArgs e)
{
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (btn4.Text == ans)
{
scoreAdd();
MessageBox.Show("Correct");
}
else
{
MessageBox.Show(ans);
}
currentRow++;
nextRow();
}
答案 0 :(得分:1)
private void button_KeyDown(object sender, KeyEventArgs e)
{
Button button = sender as Button;
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (button.Text == ans)
{
scoreAdd();
MessageBox.Show("Correct");
}
else
{
MessageBox.Show(ans);
}
currentRow++;
nextRow();
}
只需将发件人转换为Button并从中获取文字。
将所有事件按钮绑定到button_KeyDown。
这样你只有一种方法。
答案 1 :(得分:1)
为逻辑创建一般方法,如:
protected void TheLogic(string txt)
{
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (txt == ans)
{
scoreAdd();
MessageBox.Show("Correct");
}
else
{
MessageBox.Show(ans);
}
currentRow++;
nextRow();
}
然后使用相应的参数文本调用每个TheLogic
事件中的KeyDown
函数,例如,
private void btn3_KeyDown(object sender, KeyEventArgs e)
{
TheLogic(btn3.Text);
}
private void btn4_KeyDown(object sender, KeyEventArgs e)
{
TheLogic(btn4.Text);
}