Наследование. Добавить событие и показать его обработку - C#
Формулировка задачи:
На основе задания реализовать класс наследник от базового класса, добавить событие и показать его обработку.
Задание: В магазине формируется список лиц, записавшихся на покупку товара повышения спроса. Каждая запись этого списка содержит: порядковый номер, Ф.И.О., домашний адрес покупателя и дату постановки на учет. Удалить из списка все повторные записи, проверяя Ф.И.О и домашний адрес.
Вот код который я написал к заданию:
Файл Program.cs:
Файл Spravka.cs:
Листинг программы
- class Program
- {
- public static Spravka<int>[] list;
- static public void DisplayMenu()
- {
- Console.WriteLine("1. Создать лист");
- Console.WriteLine("2. Просмотреть лист...");
- Console.WriteLine("3. Открыть файл...");
- Console.WriteLine("4. Сохранить файл...");
- Console.WriteLine("ESC.Exit...");
- }
- static void CreateList()
- {
- Console.WriteLine();
- Console.Write("Список лиц: ");
- int s = int.Parse(Console.ReadLine());
- list = new Spravka<int>[s];
- for (int i = 0; i < s; i++)
- {
- Console.Write("Порядковый номер: ");
- int nomer = int.Parse(Console.ReadLine());
- Console.Write("Ф.И.О: ");
- string fio = Console.ReadLine();
- Console.Write("Дом. адрес покупателя: ");
- string adres = (Console.ReadLine());
- Console.Write("Дата постановки на учёт: ");
- string data = Console.ReadLine();
- Spravka<int> spravka = new Spravka<int>(nomer, fio, adres, data);
- list[i] = spravka;
- Console.WriteLine("Данные занесены!");
- }
- Проверка_Уник();
- }
- static void ViewList()
- {
- Console.WriteLine();
- if (list == null)
- {
- Console.WriteLine("Лист пустой!");
- return;
- }
- Console.WriteLine("Просмотр листа: ");
- for (int i = 0; i < list.Length; i++)
- {
- if (list[i] == null) continue;
- else
- {
- Console.WriteLine(list[i].ToString());
- }
- }
- }
- static void SaveToFile()
- {
- Console.WriteLine();
- if (list == null)
- {
- Console.WriteLine("Лист пустой!");
- return;
- }
- Console.Write("Введите название файла: ");
- string nf = Console.ReadLine();
- if (nf.Length == 0) nf = "text.txt";
- StreamWriter writer = new StreamWriter(nf, false);
- using (writer)
- {
- for (int i = 0; i < list.Length; i++)
- {
- writer.WriteLine(list[i]);
- }
- }
- }
- static void OpenFile()
- {
- string i = Directory.GetCurrentDirectory();
- DirectoryInfo directinfo = new DirectoryInfo(i);
- FileInfo[] flinfo = directinfo.GetFiles("*.txt");
- StreamReader streader = new StreamReader(flinfo[0].Name);
- using (streader)
- {
- string line;
- Console.WriteLine();
- while ((line = streader.ReadLine()) != null)
- {
- Console.Write("Файл открыт: \n" + line);
- }
- }
- }
- static void Main(string[] args)
- {
- Console.WriteLine("Выберите № пункта из нижеперечисленных: ");
- DisplayMenu();
- Console.Write("№ пункта: ");
- ConsoleKeyInfo cki;
- do
- {
- cki = Console.ReadKey(false);
- switch (cki.KeyChar.ToString())
- {
- case "1":
- CreateList();
- break;
- case "2":
- ViewList();
- break;
- case "3":
- OpenFile();
- break;
- case "4":
- SaveToFile();
- break;
- }
- }
- while (cki.Key != ConsoleKey.Escape);
- Console.ReadLine();
- }
- public static void Проверка_Уник()
- {
- try
- {
- for (int i = 0; i < list.Length - 1; i++)
- {
- if (list[i].fio == list[i + 1].fio && list[i].adres == list[i + 1].adres)
- {
- list[i + 1] = null;
- }
- }
- }
- catch { }
- Console.WriteLine("Удалить из списка все повторные записи, проверя Ф.И.О и Дом.адрес ");
- for (int i = 0; i < list.Length; i++)
- { Console.WriteLine(list[i]); }
- }
- }
Листинг программы
- public class Spravka<T>
- {
- private int nomer;
- public string fio;
- private T[] mass;
- public string adres;
- private string data;
- private const int MASS_SIZE = 4;
- public int сount;
- public Spravka(int nomer, string fio, string adres, string data, int ms = MASS_SIZE)
- {
- this.nomer = nomer;
- this.fio = fio;
- this.adres = adres;
- this.data = data;
- this.mass = new T[ms];
- }
- public override string ToString()
- {
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < mass.Length; i++)
- {
- sb.Append(mass[i] + " ");
- }
- return "Порядковый номер: " + nomer + " " + "Ф.И.О: " + fio + " " + "Дом. адрес покупателя: " + " " + adres + " " + "Дата постановки на учёт: " + " " + data;
- }
- }
- }
Решение задачи: «Наследование. Добавить событие и показать его обработку»
textual
Листинг программы
- using System;
- using System.Linq;
- using System.Text;
- using System.IO;
- namespace ConsoleApp1
- {
- struct Info
- {
- public int num;
- public string FIO, addres, date;
- }
- class Spisok//родительский класс
- {
- public Info[] human;
- public int n;
- public void Add()//создать список
- {
- Console.Write("Количество записей: "); n = int.Parse(Console.ReadLine());
- human = new Info[n];
- for (int i = 0; i < n; i++)
- {
- Console.WriteLine($"Запись {i + 1}");
- human[i].num = i;
- Console.Write("ФИО: "); human[i].FIO = Console.ReadLine();
- Console.Write("Адрес: "); human[i].addres = Console.ReadLine();
- Console.Write("Дата: "); human[i].date = Console.ReadLine();
- }
- Console.Clear();
- }
- public void View()//вывод содержимого
- {
- for (int i = 0; i < human.Length; i++)
- {
- if (human[i].FIO != null)
- Console.WriteLine($"{human[i].num + 1}. {human[i].FIO}; {human[i].addres}; {human[i].date}");
- }
- Console.WriteLine();
- }
- public void FileInput()//заполнение из файла
- {
- Console.Write("Полный адрес файла: "); string path = Console.ReadLine();
- if (!File.Exists(path))
- {
- Console.Clear();
- Console.WriteLine("Файла не существует!\n");
- }
- else
- {
- Console.Clear();
- n = File.ReadAllLines(path).Length;
- human = new Info[n];
- string[] s = File.ReadAllLines(path,Encoding.GetEncoding("windows-1251")).ToArray();
- for (int i = 0; i < n; i++)
- {
- string[] ss = s[i].Split('/').ToArray();
- human[i].num = i;
- human[i].FIO = ss[0];
- human[i].addres = ss[1];
- human[i].date = ss[2];
- }
- Console.WriteLine("Успешно!\n");
- }
- }
- public void SaveToFile()//вывод в файл
- {
- Console.Write("Полный адрес файла: "); string path = Console.ReadLine();
- Console.Clear();
- FileStream fcreate = File.Create(path);
- fcreate.Close();
- if (!Path.HasExtension(path))
- {
- Console.WriteLine("Файл не может быть создан!\n");
- }
- else
- {
- string[] s = new string[n];
- for (int i = 0; i < s.Length; i++)
- s[i] = $"{human[i].FIO}/{human[i].addres}/{human[i].date}";
- File.WriteAllText(path, String.Join(Environment.NewLine, s.Where(v => !v.StartsWith("/"))));
- Console.WriteLine("Успешно!\n");
- }
- }
- }
- class SpisokDel : Spisok//дочерний класс
- {
- public void Menu()//меню
- {
- int c = -1;
- do
- {
- Console.WriteLine("1.Создать список\n2.Просмотреть список\n3.Открыть файл\n4.Сохранить в файл\n5.Удалить повторные записи\n0.Выход");
- c = int.Parse(Console.ReadLine());
- Console.Clear();
- switch (c)
- {
- case 1:
- Add();
- break;
- case 2:
- View();
- break;
- case 3:
- FileInput();
- break;
- case 4:
- SaveToFile();
- break;
- case 5:
- Del();
- break;
- }
- } while (c != 0);
- }
- public void Del()//удаление одинаковых
- {
- for (int i = 0; i < human.Length - 1; i++)
- {
- for (int j = i + 1; j < human.Length; j++)
- {
- if (human[i].FIO == human[j].FIO && human[i].addres == human[j].addres)
- {
- human[j].FIO = null;
- human[j].addres = null;
- human[j].date = null;
- }
- }
- }
- Console.WriteLine("Повторные записи удалены!\n");
- }
- }
- class Program
- {
- static void Main()
- {
- SpisokDel s = new SpisokDel();
- s.Menu();
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д