需要实现 C# 计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1353935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
need implement C# Counter
提问by
I want to make increment and decrement counter. There are two buttons called X and Y. If first press X and then press Y counter should increment. If first press Y and then press X counter should decrement.
我想做递增和递减计数器。有两个按钮称为 X 和 Y。如果先按 X 再按 Y 计数器应增加。如果先按 Y 再按 X 计数器应该递减。
I am not familiar with c#. So can anyone help me please ?? :(
我对 c# 不熟悉。所以有人可以帮我吗??:(
回答by 7wp
You would want to have a variable that you want to keep track of the counter.
您可能想要一个变量来跟踪计数器。
int counter = 0;
If it is a web application then you must store this some where such as session state. then in your increment counter button:
如果它是一个 Web 应用程序,那么您必须将其存储在诸如会话状态之类的地方。然后在您的增量计数器按钮中:
counter++;
and in your decrement counter button do this:
并在您的递减计数器按钮中执行以下操作:
counter--;
回答by Paul Williams
Sounds like you need 2 variables: a counter, and the last button pressed. I'll assume this is a WinForms application, since you did not specify at the time I am writing this.
听起来您需要 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;
}
}
}
回答by Andrew
Found this on another website:
在另一个网站上找到了这个:
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();
}
}
}