我想制作增量和减量计数器。有两个按钮称为 X 和 Y。如果先按 X,然后按 Y,计数器应该增加。如果先按 Y 再按 X 计数器应该递减。
我对c#不熟悉。所以有人可以帮我吗?:(
听起来您需要 2 个变量:一个计数器和按下的最后一个按钮。我假设这是一个 WinForms 应用程序,因为您在我写这篇文章时没有指定。
class MyForm : Form
{
// From the designer code:
Button btnX;
Button btnY;
void InitializeComponent()
{
...
btnX.Clicked += btnX_Clicked;
btnY.Clicked += btnY_Clicked;
...
}
Button btnLastPressed = null;
int counter = 0;
void btnX_Clicked(object source, EventArgs e)
{
if (btnLastPressed == btnY)
{
// button Y was pressed first, so decrement the counter
--counter;
// reset the state for the next button press
btnLastPressed = null;
}
else
{
btnLastPressed = btnX;
}
}
void btnY_Clicked(object source, EventArgs e)
{
if (btnLastPressed == btnX)
{
// button X was pressed first, so increment the counter
++counter;
// reset the state for the next button press
btnLastPressed = null;
}
else
{
btnLastPressed = btnY;
}
}
}
你会想要一个变量来跟踪计数器。
int counter = 0;
如果它是一个 Web 应用程序,那么您必须将其存储在某些位置,例如会话状态。然后在您的增量计数器按钮中:
counter++;
并在您的递减计数器按钮中执行以下操作:
counter--;
在另一个网站上找到了这个:
public partial class Form1 : Form
{
//create a global private integer
private int number;
public Form1()
{
InitializeComponent();
//Intialize the variable to 0
number = 0;
//Probably a good idea to intialize the label to 0 as well
numberLabel.Text = number.ToString();
}
private void Xbutton_Click(object sender, EventArgs e)
{
//On a X Button click increment the number
number++;
//Update the label. Convert the number to a string
numberLabel.Text = number.ToString();
}
private void Ybutton_Click(object sender, EventArgs e)
{
//If number is less than or equal to 0 pop up a message box
if (number <= 0)
{
MessageBox.Show("Cannot decrement anymore. Value will be
negative");
}
else
{
//decrement the number
number--;
numberLabel.Text = number.ToString();
}
}
}