Created
October 7, 2025 10:26
-
-
Save sunmeat/8c5715750c319d7c18820c89f324c0d8 to your computer and use it in GitHub Desktop.
IComparable example C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
namespace Compare | |
{ | |
class Monster : IComparable<Monster> | |
{ | |
public string Name { get; set; } | |
public int Health { get; set; } | |
public int Ammo { get; set; } | |
public Monster(int health, int ammo, string name) | |
{ | |
Health = health; | |
Ammo = ammo; | |
Name = name; | |
} | |
public virtual void Passport() | |
{ | |
Console.WriteLine("Монстр {0} з здоров'ям = {1} та боєприпасами = {2}", Name, Health, Ammo); | |
} | |
public int CompareTo(Monster? other) | |
{ | |
// реалізує порівняння за здоров'ям (health): повертає 1 якщо поточний більший, -1 якщо менший, 0 якщо рівні | |
return Health.CompareTo(other?.Health); | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
Console.OutputEncoding = Encoding.UTF8; | |
Monster[] crowd = [ | |
new Monster(50, 50, "Кликан"), | |
new Monster(80, 80, "Хвостан"), | |
new Monster(40, 10, "Зубан") | |
]; | |
Console.WriteLine("До сортування:"); | |
foreach (Monster elem in crowd) | |
elem.Passport(); | |
Array.Sort(crowd); // сортування тепер можливе завдяки реалізації IComparable<Monster> | |
Console.WriteLine("\nПісля сортування за здоров'ям:"); | |
foreach (Monster elem in crowd) elem.Passport(); | |
} | |
} | |
} | |
// але в реалізації такого інтерфейсу є свої підводні камені, наприклад, якщо ми захочемо порівнювати не лише за здоров'ям, а й за боєприпасами чи ім'ям, | |
// то додати ще один інтерфейс IComparable<Monster> не вийде, бо клас може реалізувати лише один інтерфейс з однаковою назвою. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment