# 在 C# 中實現計數器

Haider Ali 2023年10月12日

## 在 `C#` 中實現計數器

``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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;
}
}

}
``````

``````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;
}
}
``````

`buttonB` 也是如此；如果 `LastPressed` 是 A，它將增加計數器；否則，將分配 `buttonB`。這就是你如何在 C# 中編寫一個遞增和遞減計數器的程式。

``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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.