- Класс со свойством Key, который будет использоваться для уникальной идентификации объект
- Набор предопределенных статических объектов
Код: Выделить всё
using System.Text.Json;
public sealed class Test
{
private static readonly HashSet _existingKeys = [];
public static readonly Test One = new("one");
public static readonly Test Two = new("two");
public Test(string key)
{
if (!_existingKeys.Add(key))
{
throw new ArgumentException($"Key '{key}' is already in use.");
}
Key = key;
}
public string Key { get; }
}
// Example usage
class Program
{
static void Main()
{
try
{
var three = new Test("one");
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message); // Output: Key 'one' is already in use.
}
var one = JsonSerializer.Serialize(Test.One);
try
{
var deserialized = JsonSerializer.Deserialize(one);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message); // Output: Key 'one' is already in use.
}
}
}
Обратите внимание, что меня интересует только уникальность объектов, определяемых пользователем.
Код: Выделить всё
public static readonly Test One = new("one");
Подробнее здесь: https://stackoverflow.com/questions/790 ... eated-once
Мобильная версия