Created
November 11, 2025 14:04
-
-
Save sunmeat/17746eb2cfd0ae37cf24aacec3f5f910 to your computer and use it in GitHub Desktop.
двійкова серіалізація 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; | |
| using MessagePack; // dotnet add package MessagePack | |
| namespace SerializationExample | |
| { | |
| // Every serializable non-static field and a property needs to be annotated | |
| // with the [Key] attribute. If you annotate the type with | |
| // the [MessagePackObject(keyAsPropertyName: true)] attribute, then members | |
| // don't require explicit annotations. In such case, to ignore certain | |
| // public members, use the [IgnoreMember] attribute. | |
| // https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-migration-guide/migrate-to-messagepack | |
| [MessagePackObject(keyAsPropertyName: true)] | |
| public class Cat | |
| { | |
| private string nick; | |
| private int age; | |
| public string Nick | |
| { | |
| get => nick ?? string.Empty; | |
| set => nick = value ?? string.Empty; | |
| } | |
| public int Age | |
| { | |
| get => age; | |
| set => age = Math.Max(0, value); | |
| } | |
| public bool IsAdult => Age >= 1; | |
| public Cat() | |
| { | |
| Nick = string.Empty; | |
| Age = 0; | |
| } | |
| public Cat(string nick, int age) | |
| { | |
| Nick = nick; | |
| Age = age; | |
| } | |
| public void Meow() | |
| { | |
| Console.WriteLine($"{Nick} каже: Мяу!"); | |
| } | |
| public void CelebrateBirthday() | |
| { | |
| Age++; | |
| Console.WriteLine($"Вітаємо, {Nick}! Тепер тобі {Age} років!"); | |
| } | |
| public override string ToString() | |
| { | |
| return $"Кіт {Nick}, вік: {Age}, дорослий: {IsAdult}"; | |
| } | |
| // статичний метод для створення випадкового кота | |
| public static Cat CreateRandomCat() | |
| { | |
| var random = new Random(); | |
| var names = new[] { "Локі", "Фрея", "Велес", "Бастет" }; | |
| return new Cat(names[random.Next(names.Length)], random.Next(1, 10)); | |
| } | |
| } | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| Console.OutputEncoding = Encoding.UTF8; | |
| var cat1 = new Cat("Барсик", 5); | |
| cat1.Meow(); | |
| Console.WriteLine(cat1); | |
| cat1.CelebrateBirthday(); | |
| Console.WriteLine(cat1); | |
| var cat2 = new Cat(); | |
| cat2.Nick = "Мурка"; | |
| cat2.Age = 2; | |
| Console.WriteLine(cat2); | |
| Console.WriteLine($"Чи дорослий? {cat2.IsAdult}"); | |
| var cat3 = new Cat("Барсик", 6); | |
| Console.WriteLine($"cat1 == cat3: {cat1.Equals(cat3)}"); // false, бо вік різний | |
| Console.WriteLine($"HashCode cat1: {cat1.GetHashCode()}"); | |
| // серіалізація | |
| byte[] bytes = MessagePackSerializer.Serialize(cat1); | |
| Console.WriteLine("байти після серіалізації:"); | |
| foreach (var b in bytes) | |
| { | |
| Console.Write($"{b}, "); | |
| } | |
| Console.WriteLine(); | |
| // десеріалізація | |
| var restoredCat = MessagePackSerializer.Deserialize<Cat>(bytes); | |
| Console.WriteLine($"відновлений кіт: {restoredCat}"); | |
| // запис у файл | |
| string filePath = "cat.msgpack"; | |
| File.WriteAllBytes(filePath, bytes); | |
| Console.WriteLine($"дані збережено у файл: {filePath}"); | |
| // читання з файлу | |
| byte[] fileBytes = File.ReadAllBytes(filePath); | |
| var catFromFile = MessagePackSerializer.Deserialize<Cat>(fileBytes); | |
| Console.WriteLine($"кіт з файлу: {catFromFile}"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment