Создаем портфолио за 1 месяц
К концу месяца: 4 классных проекта в вашем портфолио! Стоимость: 100$. Подробности...
1413 of 1492 menu
◀ ▶

CollectionBuilder

После атрибута можно писать Gate g = [1, 2, 3];. Метод Create принимает ReadOnlySpan<int> и запоминает длину. Нужен using System.Runtime.CompilerServices.

Синтаксис

[CollectionBuilder(typeof(Gate), nameof(Gate.Create))] readonly struct Gate { }

Пример

Давайте собрать Gate литералом [1, 2, 3]:

using System; using System.Runtime.CompilerServices; [CollectionBuilder(typeof(Gate), nameof(Gate.Create))] readonly struct Gate { public int Count { get; } Gate(int count) { Count = count; } public static Gate Create(ReadOnlySpan<int> items) { return new Gate(items.Length); } } class Program { static void Main() { Gate g = [1, 2, 3]; int res = g.Count; Console.WriteLine(res); } }

Результат выполнения кода:

3

Пример

Давайте собрать пустой литерал:

using System; using System.Runtime.CompilerServices; [CollectionBuilder(typeof(Gate), nameof(Gate.Create))] readonly struct Gate { public int Count { get; } Gate(int count) { Count = count; } public static Gate Create(ReadOnlySpan<int> items) { return new Gate(items.Length); } } class Program { static void Main() { Gate g = []; int res = g.Count; Console.WriteLine(res); } }

Результат выполнения кода:

0

Пример

Давайте вызвать Create напрямую:

using System; using System.Runtime.CompilerServices; [CollectionBuilder(typeof(Gate), nameof(Gate.Create))] readonly struct Gate { public int Count { get; } Gate(int count) { Count = count; } public static Gate Create(ReadOnlySpan<int> items) { return new Gate(items.Length); } } class Program { static void Main() { int[] data = { 1, 2, 3 }; Gate g = Gate.Create(data); int res = g.Count; Console.WriteLine(res); } }

Результат выполнения кода:

3

Смотрите также

← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить