Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created November 11, 2025 14:07
Show Gist options
  • Select an option

  • Save sunmeat/1df1828358357123a17a4e0ed70a0ee5 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/1df1828358357123a17a4e0ed70a0ee5 to your computer and use it in GitHub Desktop.
практика на двійкову серіалізацію
using System.Collections.Generic;
using System.Text;
namespace SuperHeroExample
{
public class Human : IEquatable<Human>
{
// приватні поля для зберігання даних
private string name;
private int age;
public string Name
{
get => name ?? string.Empty;
set => name = value ?? string.Empty;
}
public int Age
{
get => age;
set => age = Math.Max(0, value); // вік не може бути від'ємним
}
public bool IsAdult => Age >= 18; // властивість для перевірки повноліття
// конструктор без параметрів
public Human()
{
Name = string.Empty;
Age = 0;
}
// параметризований конструктор
public Human(string name, int age)
{
Name = name;
Age = age;
}
// метод для представлення себе
public void Introduce()
{
Console.WriteLine($"Привіт, мене звати {Name}, мені {Age} років.");
}
// перевизначення ToString для зручного виведення
public override string ToString()
{
return $"Людина: {Name}, вік: {Age}, повнолітній: {IsAdult}";
}
// перевизначення GetHashCode на основі унікальних властивостей
public override int GetHashCode()
{
return HashCode.Combine(Name, Age);
}
// реалізація Equals для порівняння об'єктів
public bool Equals(Human other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Name == other.Name && Age == other.Age;
}
public override bool Equals(object obj) => Equals(obj as Human);
}
public enum HeroType
{
Hero,
Villain,
AntiHero
}
public class SuperPowers
{
// приватні поля
private bool isUnique;
private List<string> abilities;
public bool IsUnique
{
get => isUnique;
set => isUnique = value;
}
public List<string> Abilities
{
get => abilities ?? new List<string>();
set => abilities = value ?? new List<string>();
}
// конструктор без параметрів
public SuperPowers()
{
IsUnique = true;
Abilities = new List<string>();
}
// параметризований конструктор
public SuperPowers(bool isUnique, List<string> abilities)
{
IsUnique = isUnique;
Abilities = abilities ?? new List<string>();
}
// метод для додавання здібності
public void AddAbility(string ability)
{
if (!string.IsNullOrWhiteSpace(ability) && !Abilities.Contains(ability))
{
Abilities.Add(ability);
Console.WriteLine($"Додано здібність: {ability}");
}
}
// метод для видалення здібності
public void RemoveAbility(string ability)
{
if (Abilities.Remove(ability))
{
Console.WriteLine($"Видалено здібність: {ability}");
}
else
{
Console.WriteLine($"Здібність '{ability}' не знайдено.");
}
}
// метод для отримання випадкової здібності
public string GetRandomAbility()
{
if (Abilities.Count == 0) return "немає здібностей";
var random = new Random();
return Abilities[random.Next(Abilities.Count)];
}
// перевизначення ToString
public override string ToString()
{
var skillsList = string.Join(", ", Abilities);
return $"Суперсили: унікальні: {IsUnique}, здібності: [{skillsList}]";
}
}
public class SuperHero : Human, IEquatable<SuperHero>
{
// приватні поля
private bool isEvil;
private SuperPowers superPowers;
private HeroType heroType;
public bool IsEvil
{
get => isEvil;
set => isEvil = value;
}
public SuperPowers SuperPowers
{
get => superPowers ?? new SuperPowers();
set => superPowers = value ?? new SuperPowers();
}
public HeroType HeroType
{
get => heroType;
set => heroType = value;
}
// конструктор без параметрів
public SuperHero() : base()
{
IsEvil = false;
SuperPowers = new SuperPowers();
HeroType = HeroType.Hero;
}
// параметризований конструктор
public SuperHero(string name, int age, bool isEvil, HeroType type) : base(name, age)
{
IsEvil = isEvil;
SuperPowers = new SuperPowers();
HeroType = type;
}
// метод для використання суперсили
public void UseSuperPower()
{
var power = SuperPowers.GetRandomAbility();
if (IsEvil)
{
Console.WriteLine($"{Name} використовує злу силу: {power}!");
}
else
{
Console.WriteLine($"{Name} використовує героїчну силу: {power}!");
}
}
// метод для розкриття ідентичності
public void RevealIdentity()
{
Console.WriteLine($"Таємна ідентичність {Name} розкрита! Тип: {HeroType}");
}
// перевизначення ToString
public override string ToString()
{
return $"{base.ToString()}, герой: {HeroType}, злий: {IsEvil}, {SuperPowers}";
}
// перевизначення GetHashCode
public override int GetHashCode()
{
return HashCode.Combine(base.GetHashCode(), IsEvil, HeroType, SuperPowers);
}
// реалізація Equals
public bool Equals(SuperHero other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return base.Equals(other) && IsEvil == other.IsEvil && HeroType == other.HeroType && Equals(SuperPowers, other.SuperPowers);
}
public override bool Equals(object obj) => Equals(obj as SuperHero);
// статичний метод для створення випадкового супергероя
public static SuperHero CreateRandomHero()
{
var random = new Random();
var names = new[] { "Невидимий Снайпер", "Швидкісний Вітер", "Вогняний Щит", "Крижаний Бур" };
var types = (HeroType[])Enum.GetValues(typeof(HeroType));
var abilities = new List<string> { "невидимість", "суперзір", "телепортація", "контроль часу" };
abilities.AddRange(new[] { "кислотне дихання", "звуковий крик", "відродження" });
var hero = new SuperHero(names[random.Next(names.Length)], random.Next(18, 60), random.Next(2) == 1, types[random.Next(types.Length)]);
for (int i = 0; i < random.Next(3, 6); i++)
{
hero.SuperPowers.AddAbility(abilities[random.Next(abilities.Count)]);
}
return hero;
}
}
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment