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
Смотрите также
-
OverloadResolutionPriority,
выбор перегрузки -
ModuleInitializer,
загрузка модуля -
Attribute,
базовый класс -
Атрибут,
обзор