Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Задание 3

Задание: Напишите класс Button, который имеет свойство Text типа string и событие типа EventHandler с именем Click, которое возникает при нажатии на кнопку. Затем напишите аксессоры для этого события: add и remove, которые контролируют, сколько подписчиков может иметь это событие. Например, вы можете ограничить максимальное количество подписчиков до трех или запретить добавлять один и тот же подписчик дважды. Затем напишите несколько методов, которые могут быть подписаны на это событие, например, выводящие на консоль текст кнопки или меняющие его цвет. Продемонстрируйте работу этих методов в методе Main.

Результат:

<img width="316" height="407" alt="изображение" src="https://github.com/user-attachments/assets/5d6cf54c-2489-419d-aaa0-37db8f5b8d81" />
115 changes: 81 additions & 34 deletions kt8888/Program.cs
Original file line number Diff line number Diff line change
@@ -1,62 +1,109 @@
using System;
using System.IO;
using System.Collections.Generic;

namespace kt8888
{
public class BankAccount
public class Button
{
private decimal balance;
private string text;
private EventHandler clickEvent;
private List<EventHandler> subscribers = new List<EventHandler>();

public decimal Balance
public string Text
{
get { return balance; }
private set
{
balance = value;
BalanceChanged?.Invoke(balance);
}
get { return text; }
set { text = value; }
}

public event Action<decimal> BalanceChanged;

public void Deposit(decimal amount)
public event EventHandler Click
{
Balance += amount;
}
add
{
if (subscribers.Count >= 3)
{
Console.WriteLine("cannot add more than 3 subscribers");
return;
}

public void Withdraw(decimal amount)
{
if (amount <= Balance)
if (subscribers.Contains(value))
{
Console.WriteLine("this subscriber is already added");
return;
}

subscribers.Add(value);
clickEvent += value;
Console.WriteLine("subscriber added successfully");
}
remove
{
Balance -= amount;
subscribers.Remove(value);
clickEvent -= value;
Console.WriteLine("subscriber removed successfully");
}
}
}

public class Logger
{
public Logger(BankAccount account)
public void SimulateClick()
{
account.BalanceChanged += (balance) =>
{
File.AppendAllText("log.txt", $"balance {balance}\n");
};
Console.WriteLine($"\nbutton '{Text}' clicked");
clickEvent?.Invoke(this, EventArgs.Empty);
}
}

class Program
{
static void Main()
{
BankAccount account1 = new BankAccount();
Logger logger1 = new Logger(account1);
Button button1 = new Button();
button1.Text = "button";

void PrintText(object sender, EventArgs e)
{
Console.WriteLine("button text " + ((Button)sender).Text);
}

void ChangeColor(object sender, EventArgs e)
{
Console.WriteLine("changing button color to red");
}

void ShowMessage(object sender, EventArgs e)
{
Console.WriteLine("button was clicked");
}

void FourthSubscriber(object sender, EventArgs e)
{
Console.WriteLine("this is the fourth subscriber not work");
}

// подписка методы
Console.WriteLine();
button1.Click += PrintText;
button1.Click += ChangeColor;
button1.Click += ShowMessage;

// четвертый подписчик
Console.WriteLine();
button1.Click += FourthSubscriber;

// существующий подписчик
Console.WriteLine();
button1.Click += PrintText;

// нажатие кнопки
Console.WriteLine();
button1.SimulateClick();

// удаление и добавление подписчикв
Console.WriteLine();
button1.Click -= ShowMessage;
button1.Click += FourthSubscriber;

account1.Deposit(1000);
account1.Withdraw(500);
account1.Deposit(300);
//нажатие кнопки
Console.WriteLine();
button1.SimulateClick();

Console.WriteLine("final balance " + account1.Balance);
Console.ReadLine();
}
}
}