Метод ToImmutableArray
Метод ToImmutableArray является расширением
для IEnumerable<T>, которое строит
ImmutableArray<T>.
Синтаксис
ImmutableArray<T> arr = source.ToImmutableArray();
Пример
Давайте заморозим List:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
List<int> nums = new List<int> {1, 2, 3, 4, 5};
ImmutableArray<int> arr = nums.ToImmutableArray();
Console.WriteLine(string.Join(" ", arr));
}
}
Результат выполнения кода:
1 2 3 4 5
Пример
Давайте изменить List после freeze:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
List<int> nums = new List<int> {1, 2, 3, 4, 5};
ImmutableArray<int> arr = nums.ToImmutableArray();
nums[0] = 10;
Console.WriteLine(arr[0]);
}
}
Результат выполнения кода:
1
Пример
Давайте создать из массива int:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
ImmutableArray<int> arr = new[] {1, 2, 3, 4, 5}.ToImmutableArray();
Console.WriteLine(arr.Length);
}
}
Результат выполнения кода:
5
Пример
Давайте заморозить строки:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
List<string> items = new List<string> {"a", "b", "c", "d", "e"};
ImmutableArray<string> arr = items.ToImmutableArray();
Console.WriteLine(arr[2]);
}
}
Результат выполнения кода:
"c"
Смотрите также
-
метод
ToImmutableList,
который замораживает список -
метод
ToArray,
который создаёт изменяемый массив -
метод
Add,
который расширяет immutable массив -
класс
ImmutableArray,
который хранит результат