|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | +using System.Runtime.InteropServices; |
| 4 | + |
| 5 | +namespace CollectionTest; |
| 6 | + |
| 7 | +internal class ImmutableListTest |
| 8 | +{ |
| 9 | + |
| 10 | + #region Constants & Statics |
| 11 | + |
| 12 | + public static void CopyOnWriteTest() |
| 13 | + { |
| 14 | + var array = new[] { 1, 2, 3, 4 }; |
| 15 | + var immutable = array.ToImmutableList(); |
| 16 | + |
| 17 | + var asImmutable = ImmutableCollectionsMarshal.AsImmutableArray(array); |
| 18 | + var as2 = Unsafe.As<int[], ImmutableArray<int>>(ref array); |
| 19 | + var as3 = ImmutableArray.Create(array); |
| 20 | + |
| 21 | + array[0] = 100; |
| 22 | + Console.WriteLine(immutable[0]); // 1 发生复制 |
| 23 | + Console.WriteLine(asImmutable[0]); // 100 |
| 24 | + Console.WriteLine(as2[0]); // 100 |
| 25 | + Console.WriteLine(as3[0]); // 1 发生复制 |
| 26 | + |
| 27 | + Console.WriteLine(); |
| 28 | + var newImmutable = asImmutable.SetItem(1, 200); |
| 29 | + Console.WriteLine(array[1]); // 2 |
| 30 | + Console.WriteLine(newImmutable[1]); // 200 |
| 31 | + } |
| 32 | + |
| 33 | + public static void ImmutableInterlockedTest() |
| 34 | + { |
| 35 | + var list = ImmutableList<int>.Empty; |
| 36 | + |
| 37 | + // 多线程安全添加 |
| 38 | + ImmutableInterlocked.Update(ref list, l => l.Add(1)); |
| 39 | + ImmutableInterlocked.Update(ref list, l => l.Add(2)); |
| 40 | + |
| 41 | + Console.WriteLine(string.Join(", ", list)); // 1, 2 |
| 42 | + } |
| 43 | + |
| 44 | + public static void Test() |
| 45 | + { |
| 46 | + var list = new List<int>(); |
| 47 | + var readOnly = list.AsReadOnly(); |
| 48 | + var immutable = list.ToImmutableList(); |
| 49 | + |
| 50 | + list.Add(1); |
| 51 | + Console.WriteLine(readOnly.Count); // 1 |
| 52 | + Console.WriteLine(immutable.Count); // 0 |
| 53 | + |
| 54 | + var newList = immutable.Add(2); |
| 55 | + Console.WriteLine(immutable.Count); // 0 |
| 56 | + Console.WriteLine(newList.Count); // 1 |
| 57 | + } |
| 58 | + |
| 59 | + #endregion |
| 60 | + |
| 61 | +} |
0 commit comments