fork download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. // Визначення перелічуваного типу Rank
  7. public enum Rank
  8. {
  9. Junior,
  10. Middle,
  11. Senior,
  12. Expert
  13. }
  14.  
  15. // Інтерфейс IDateAndCopy
  16. public interface IDateAndCopy
  17. {
  18. object DeepCopy();
  19. DateTime Date { get; set; }
  20. }
  21.  
  22. // Клас License (без змін з лабораторної роботи 2)
  23. public class License
  24. {
  25. public string LicenseNumber { get; set; }
  26. public string Category { get; set; }
  27. public DateTime IssueDate { get; set; }
  28. public DateTime ExpiryDate { get; set; }
  29.  
  30. public License(string licenseNumber, string category, DateTime issueDate, DateTime expiryDate)
  31. {
  32. LicenseNumber = licenseNumber;
  33. Category = category;
  34. IssueDate = issueDate;
  35. ExpiryDate = expiryDate;
  36. }
  37.  
  38. public override string ToString()
  39. {
  40. return $"License: {LicenseNumber}, Category: {Category}, Issued: {IssueDate:d}, Expires: {ExpiryDate:d}";
  41. }
  42. }
  43.  
  44. // Клас Person з реалізацією інтерфейсу IDateAndCopy
  45. public class Person : IDateAndCopy, IEquatable<Person>
  46. {
  47. protected string firstName;
  48. protected string lastName;
  49. protected DateTime birthDate;
  50.  
  51. public Person(string firstName, string lastName, DateTime birthDate)
  52. {
  53. this.firstName = firstName;
  54. this.lastName = lastName;
  55. this.birthDate = birthDate;
  56. }
  57.  
  58. public Person() : this("John", "Doe", new DateTime(1990, 1, 1)) { }
  59.  
  60. // Властивості
  61. public string FirstName
  62. {
  63. get => firstName;
  64. set => firstName = value;
  65. }
  66.  
  67. public string LastName
  68. {
  69. get => lastName;
  70. set => lastName = value;
  71. }
  72.  
  73. public DateTime BirthDate
  74. {
  75. get => birthDate;
  76. set => birthDate = value;
  77. }
  78.  
  79. public int BirthYear
  80. {
  81. get => birthDate.Year;
  82. set => birthDate = new DateTime(value, birthDate.Month, birthDate.Day);
  83. }
  84.  
  85. // Реалізація інтерфейсу IDateAndCopy
  86. public DateTime Date { get; set; } = DateTime.Now;
  87.  
  88. public virtual object DeepCopy()
  89. {
  90. return new Person(firstName, lastName, birthDate) { Date = this.Date };
  91. }
  92.  
  93. // Перевизначення методів Equals та GetHashCode
  94. public override bool Equals(object obj)
  95. {
  96. if (obj is Person other)
  97. return Equals(other);
  98. return false;
  99. }
  100.  
  101. public bool Equals(Person other)
  102. {
  103. if (other is null) return false;
  104. return firstName == other.firstName &&
  105. lastName == other.lastName &&
  106. birthDate == other.birthDate;
  107. }
  108.  
  109. public override int GetHashCode()
  110. {
  111. return HashCode.Combine(firstName, lastName, birthDate);
  112. }
  113.  
  114. public static bool operator ==(Person left, Person right)
  115. {
  116. if (left is null) return right is null;
  117. return left.Equals(right);
  118. }
  119.  
  120. public static bool operator !=(Person left, Person right)
  121. {
  122. return !(left == right);
  123. }
  124.  
  125. public override string ToString()
  126. {
  127. return $"{firstName} {lastName}, Born: {birthDate:d}";
  128. }
  129. }
  130.  
  131. // Клас Client, який успадковується від Person
  132. public class Client : Person
  133. {
  134. public string IssueType { get; set; }
  135. public DateTime DeliveryDate { get; set; }
  136.  
  137. public Client(Person person, string issueType, DateTime deliveryDate)
  138. : base(person.FirstName, person.LastName, person.BirthDate)
  139. {
  140. IssueType = issueType;
  141. DeliveryDate = deliveryDate;
  142. }
  143.  
  144. public Client() : base()
  145. {
  146. IssueType = "Engine problem";
  147. DeliveryDate = DateTime.Now;
  148. }
  149.  
  150. public override string ToString()
  151. {
  152. return $"{base.ToString()}, Issue: {IssueType}, Delivery: {DeliveryDate:d}";
  153. }
  154.  
  155. public override object DeepCopy()
  156. {
  157. return new Client((Person)base.DeepCopy(), IssueType, DeliveryDate);
  158. }
  159. }
  160.  
  161. // Клас StationWorker, який успадковується від Person
  162. public class StationWorker : Person, IEnumerable<License>, IDateAndCopy
  163. {
  164. private string specialization;
  165. private Rank rank;
  166. private int experience;
  167. private List<License> licenses = new List<License>();
  168. private List<Client> clients = new List<Client>();
  169.  
  170. public StationWorker(Person person, string specialization, Rank rank, int experience)
  171. : base(person.FirstName, person.LastName, person.BirthDate)
  172. {
  173. this.specialization = specialization;
  174. this.rank = rank;
  175. Experience = experience; // Використовуємо властивість для валідації
  176. }
  177.  
  178. public StationWorker() : base()
  179. {
  180. specialization = "Mechanic";
  181. rank = Rank.Junior;
  182. Experience = 1;
  183. }
  184.  
  185. // Властивості
  186. public Person PersonData
  187. {
  188. get => new Person(firstName, lastName, birthDate);
  189. set
  190. {
  191. firstName = value.FirstName;
  192. lastName = value.LastName;
  193. birthDate = value.BirthDate;
  194. }
  195. }
  196.  
  197. public License FirstLicense => licenses.Count > 0 ? licenses[0] : null;
  198.  
  199. public List<Client> Clients
  200. {
  201. get => clients;
  202. set => clients = value ?? new List<Client>();
  203. }
  204.  
  205. public int Experience
  206. {
  207. get => experience;
  208. set
  209. {
  210. if (value < 0 || value > 100)
  211. throw new ArgumentOutOfRangeException(nameof(Experience),
  212. "Experience must be between 0 and 100 years");
  213. experience = value;
  214. }
  215. }
  216.  
  217. public string Specialization
  218. {
  219. get => specialization;
  220. set => specialization = value;
  221. }
  222.  
  223. public Rank Rank
  224. {
  225. get => rank;
  226. set => rank = value;
  227. }
  228.  
  229. public List<License> Licenses
  230. {
  231. get => licenses;
  232. set => licenses = value ?? new List<License>();
  233. }
  234.  
  235. // Методи
  236. public void AddLicense(params License[] newLicenses)
  237. {
  238. licenses.AddRange(newLicenses);
  239. }
  240.  
  241. public override string ToString()
  242. {
  243. string licensesStr = string.Join("\n ", licenses.Select(l => l.ToString()));
  244. string clientsStr = string.Join("\n ", clients.Select(c => c.ToString()));
  245.  
  246. return $"{base.ToString()}, Specialization: {specialization}, Rank: {rank}, " +
  247. $"Experience: {experience} years\nLicenses:\n {licensesStr}\nClients:\n {clientsStr}";
  248. }
  249.  
  250. public string ToShortString()
  251. {
  252. return $"{base.ToString()}, Specialization: {specialization}, Rank: {rank}, " +
  253. $"Experience: {experience} years, Total Clients: {clients.Count}";
  254. }
  255.  
  256. public override object DeepCopy()
  257. {
  258. var copy = new StationWorker(
  259. (Person)base.DeepCopy(),
  260. specialization,
  261. rank,
  262. experience
  263. );
  264.  
  265. copy.licenses = licenses.Select(l => new License(l.LicenseNumber, l.Category, l.IssueDate, l.ExpiryDate)).ToList();
  266. copy.clients = clients.Select(c => (Client)c.DeepCopy()).ToList();
  267.  
  268. return copy;
  269. }
  270.  
  271. // Ітератори
  272. public IEnumerable<Client> GetRepairClients()
  273. {
  274. foreach (var client in clients)
  275. {
  276. yield return client;
  277. }
  278. }
  279.  
  280. public IEnumerable<Client> GetClientsByIssue(string issueType)
  281. {
  282. foreach (var client in clients.Where(c => c.IssueType.Equals(issueType, StringComparison.OrdinalIgnoreCase)))
  283. {
  284. yield return client;
  285. }
  286. }
  287.  
  288. // Додатковий ітератор для клієнтів, які віддали авто більше місяця тому
  289. public IEnumerable<Client> GetClientsWithOldRepairs()
  290. {
  291. foreach (var client in clients.Where(c => (DateTime.Now - c.DeliveryDate).TotalDays > 30))
  292. {
  293. yield return client;
  294. }
  295. }
  296.  
  297. // Реалізація IEnumerable<License> для перебору ліцензій до 2010 року
  298. public IEnumerator<License> GetEnumerator()
  299. {
  300. return new StationWorkerEnumerator(this);
  301. }
  302.  
  303. IEnumerator IEnumerable.GetEnumerator()
  304. {
  305. return GetEnumerator();
  306. }
  307.  
  308. // Допоміжний клас для перебору ліцензій до 2010 року
  309. private class StationWorkerEnumerator : IEnumerator<License>
  310. {
  311. private StationWorker stationWorker;
  312. private int currentIndex = -1;
  313.  
  314. public StationWorkerEnumerator(StationWorker sw)
  315. {
  316. stationWorker = sw;
  317. }
  318.  
  319. public License Current => stationWorker.licenses[currentIndex];
  320.  
  321. object IEnumerator.Current => Current;
  322.  
  323. public bool MoveNext()
  324. {
  325. currentIndex++;
  326. while (currentIndex < stationWorker.licenses.Count)
  327. {
  328. if (stationWorker.licenses[currentIndex].IssueDate.Year < 2010)
  329. return true;
  330. currentIndex++;
  331. }
  332. return false;
  333. }
  334.  
  335. public void Reset()
  336. {
  337. currentIndex = -1;
  338. }
  339.  
  340. public void Dispose() { }
  341. }
  342. }
  343.  
  344. // Головний клас програми
  345. class Program
  346. {
  347. static void Main()
  348. {
  349. Console.WriteLine("=== 1. Перевірка рівності об'єктів Person ===");
  350. Person person1 = new Person("Ivan", "Petrenko", new DateTime(1985, 5, 15));
  351. Person person2 = new Person("Ivan", "Petrenko", new DateTime(1985, 5, 15));
  352.  
  353. Console.WriteLine($"References equal: {ReferenceEquals(person1, person2)}");
  354. Console.WriteLine($"Objects equal: {person1 == person2}");
  355. Console.WriteLine($"Hash code 1: {person1.GetHashCode()}");
  356. Console.WriteLine($"Hash code 2: {person2.GetHashCode()}");
  357.  
  358. Console.WriteLine("\n=== 2. Створення StationWorker з ліцензіями та клієнтами ===");
  359. StationWorker worker = new StationWorker(person1, "Engine Specialist", Rank.Senior, 10);
  360.  
  361. // Додаємо ліцензії
  362. worker.AddLicense(
  363. new License("LIC001", "A", new DateTime(2005, 3, 10), new DateTime(2015, 3, 10)),
  364. new License("LIC002", "B", new DateTime(2015, 6, 20), new DateTime(2025, 6, 20))
  365. );
  366.  
  367. // Додаємо клієнтів
  368. worker.Clients.AddRange(new[]
  369. {
  370. new Client(new Person("Oleg", "Sydorenko", new DateTime(1990, 8, 12)),
  371. "Engine failure", DateTime.Now),
  372. new Client(new Person("Maria", "Ivanova", new DateTime(1988, 2, 25)),
  373. "Transmission issue", DateTime.Now.AddDays(-5)),
  374. new Client(new Person("Petro", "Koval", new DateTime(1975, 11, 3)),
  375. "Brake system", DateTime.Now.AddMonths(-2))
  376. });
  377.  
  378. Console.WriteLine(worker);
  379.  
  380. Console.WriteLine("\n=== 3. Властивість PersonData ===");
  381. Console.WriteLine(worker.PersonData);
  382.  
  383. Console.WriteLine("\n=== 4. Тестування DeepCopy ===");
  384. StationWorker copy = (StationWorker)worker.DeepCopy();
  385.  
  386. // Змінюємо оригінал
  387. worker.FirstName = "ChangedName";
  388. if (worker.Clients.Count > 0)
  389. worker.Clients[0].IssueType = "ChangedIssue";
  390.  
  391. Console.WriteLine("Original after changes:");
  392. Console.WriteLine(worker.ToShortString());
  393. Console.WriteLine("\nCopy (should be unchanged):");
  394. Console.WriteLine(copy.ToShortString());
  395.  
  396. Console.WriteLine("\n=== 5. Тестування валідації стажу ===");
  397. try
  398. {
  399. worker.Experience = 150; // Некоректне значення
  400. }
  401. catch (ArgumentOutOfRangeException ex)
  402. {
  403. Console.WriteLine($"Exception caught: {ex.Message}");
  404. }
  405.  
  406. Console.WriteLine("\n=== 6. Ітератор для клієнтів з сьогоднішньою датою ===");
  407. Console.WriteLine("Clients with today's delivery date:");
  408. foreach (var client in worker.GetRepairClients().Where(c => c.DeliveryDate.Date == DateTime.Today))
  409. {
  410. Console.WriteLine($" {client}");
  411. }
  412.  
  413. Console.WriteLine("\n=== 7. Ітератор для клієнтів з конкретною несправністю ===");
  414. Console.WriteLine("Clients with 'Engine failure':");
  415. foreach (var client in worker.GetClientsByIssue("Engine failure"))
  416. {
  417. Console.WriteLine($" {client}");
  418. }
  419.  
  420. Console.WriteLine("\n=== 8. Перебір ліцензій до 2000 року (IEnumerable) ===");
  421. Console.WriteLine("Licenses issued before 2000:");
  422. foreach (var license in worker)
  423. {
  424. Console.WriteLine($" {license}");
  425. }
  426.  
  427. Console.WriteLine("\n=== 9. Клієнти з ремонтом більше місяця тому ===");
  428. Console.WriteLine("Clients with repairs older than 1 month:");
  429. foreach (var client in worker.GetClientsWithOldRepairs())
  430. {
  431. Console.WriteLine($" {client}");
  432. }
  433. }
  434. }
Success #stdin #stdout 0.1s 35112KB
stdin
Standard input is empty
stdout
=== 1. Перевірка рівності об'єктів Person ===
References equal: False
Objects equal: True
Hash code 1: 1373849390
Hash code 2: 1373849390

=== 2. Створення StationWorker з ліцензіями та клієнтами ===
Ivan Petrenko, Born: 5/15/1985, Specialization: Engine Specialist, Rank: Senior, Experience: 10 years
Licenses:
  License: LIC001, Category: A, Issued: 3/10/2005, Expires: 3/10/2015
  License: LIC002, Category: B, Issued: 6/20/2015, Expires: 6/20/2025
Clients:
  Oleg Sydorenko, Born: 8/12/1990, Issue: Engine failure, Delivery: 9/1/2025
  Maria Ivanova, Born: 2/25/1988, Issue: Transmission issue, Delivery: 8/27/2025
  Petro Koval, Born: 11/3/1975, Issue: Brake system, Delivery: 7/1/2025

=== 3. Властивість PersonData ===
Ivan Petrenko, Born: 5/15/1985

=== 4. Тестування DeepCopy ===
Original after changes:
ChangedName Petrenko, Born: 5/15/1985, Specialization: Engine Specialist, Rank: Senior, Experience: 10 years, Total Clients: 3

Copy (should be unchanged):
Ivan Petrenko, Born: 5/15/1985, Specialization: Engine Specialist, Rank: Senior, Experience: 10 years, Total Clients: 3

=== 5. Тестування валідації стажу ===
Exception caught: Experience must be between 0 and 100 years (Parameter 'Experience')

=== 6. Ітератор для клієнтів з сьогоднішньою датою ===
Clients with today's delivery date:
  Oleg Sydorenko, Born: 8/12/1990, Issue: ChangedIssue, Delivery: 9/1/2025

=== 7. Ітератор для клієнтів з конкретною несправністю ===
Clients with 'Engine failure':

=== 8. Перебір ліцензій до 2000 року (IEnumerable) ===
Licenses issued before 2000:
  License: LIC001, Category: A, Issued: 3/10/2005, Expires: 3/10/2015

=== 9. Клієнти з ремонтом більше місяця тому ===
Clients with repairs older than 1 month:
  Petro Koval, Born: 11/3/1975, Issue: Brake system, Delivery: 7/1/2025