在 C# 中实现计数器
在本指南中,我们将了解如何使用两个按钮在 C# 中创建递增和递减计数器。例如,如果有两个按钮,A 和 B。
按 A 和 B 应该增加计数器,按 A 和 B 应该分别减少计数器。让我们深入研究本指南并学习自己。
在 C#
中实现计数器
在这个问题中,我们需要两个变量。首先,我们需要一个计数器变量,其次,我们需要一个检查最后按下的按钮。
让我们看看我们将如何做到这一点。首先,我们需要创建事件委托,因此每当单击按钮时都会发生特定事件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace counter
{
class MyForm : Form
{
// Window From Code
Button buttonA;
Button buttonB;
void InitializeComponent()
{
buttonA.Clicked += Button_A_Click; // btn_Clicked Event.. delgates..
buttonB.Clicked += Button_B_Click;
}
}
}
在上面的代码中,我们制作了两个按钮并分配了事件委托。每当单击 buttonA
时,函数 Button_A_Click
将运行。
接下来,我们需要有两个变量。看一看。
Button LastPressed = null; //Track which button was last pressed.
int counter = 0; // initializing Counter Value
LastPressed
将跟踪最后按下的按钮,计数器将跟踪递增和递减。接下来我们需要有两个函数来跟踪这一切。
void Button_A_Click(object source, EventArgs e)
{
if (LastPressed == buttonB) //verifying which button is being pressed.
{
// button B was pressed first, so decrement the counter
--counter; //decrementing...
// reset state for the next button press
LastPressed = null; //again button set to null for next tracking..
}
else
{
LastPressed = buttonA; // assging which button was pressed.
}
}
void Button_B_Click(object source, EventArgs e)
{
if (LastPressed == buttonA)
{
// buttonA was pressed 1st, so increment the counter
++counter;
// reset state for the next button press
LastPressed = null;
}
else
{
LastPressed = buttonB;
}
}
如果点击 buttonA
,程序将检查 LastPressed
中的值。如果是 buttonB
,计数器将递减;如果没有,buttonA
将被分配给 LastPressed
。
buttonB
也是如此;如果 LastPressed
是 A,它将增加计数器;否则,将分配 buttonB
。这就是你如何在 C# 中编写一个递增和递减计数器的程序。
以下是完整代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace counter
{
class MyForm : Form
{
// Window From Code
Button buttonA;
Button buttonB;
void InitializeComponent()
{
buttonA.Clicked += Button_A_Click; // btnB_Clicked Event.. delgates..
buttonB.Clicked += Button_B_Click;
}
Button LastPressed = null; //Track which button was last pressed.
int counter = 0; // initializing Counter Value
void Button_A_Click(object source, EventArgs e)
{
if (LastPressed == buttonB) //verifying which button is being pressed.
{
// button B was pressed first, so decrement the counter
--counter; //decrementing...
// reset state for the next button press
LastPressed = null; //again button set to null for next tracking..
}
else
{
LastPressed = buttonA; // assging which button was pressed.
}
}
void Button_B_Click(object source, EventArgs e)
{
if (LastPressed == buttonA)
{
// buttonA was pressed 1st, so increment the counter
++counter;
// reset state for the next button press
LastPressed = null;
}
else
{
LastPressed = buttonB;
}
}
}
}
Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.
LinkedIn