44
55namespace CollectionTest ;
66
7- internal class ImmutableListTest
7+ public static class ImmutableListTest
88{
99
1010 #region Constants & Statics
@@ -35,12 +35,53 @@ public static void ImmutableInterlockedTest()
3535 var list = ImmutableList < int > . Empty ;
3636
3737 // 多线程安全添加
38- ImmutableInterlocked . Update ( ref list , l => l . Add ( 1 ) ) ;
39- ImmutableInterlocked . Update ( ref list , l => l . Add ( 2 ) ) ;
38+ _ = ImmutableInterlocked . Update ( ref list , l => l . Add ( 1 ) ) ;
39+ _ = ImmutableInterlocked . Update ( ref list , l => l . Add ( 2 ) ) ;
4040
4141 Console . WriteLine ( string . Join ( ", " , list ) ) ; // 1, 2
4242 }
4343
44+ public static void RefChange_Test ( )
45+ {
46+ var list = new List < RefType > ( [ new RefType ( ) , new RefType ( ) , new RefType ( ) , new RefType ( ) ] ) ;
47+
48+ var readOnly = list . AsReadOnly ( ) ;
49+ var immutable = list . ToImmutableList ( ) ;
50+
51+ immutable [ 0 ] . StrProp = "abc" ;
52+
53+ Console . WriteLine ( list [ 0 ] . StrProp ) ;
54+ Console . WriteLine ( readOnly [ 0 ] . StrProp ) ;
55+ Console . WriteLine ( immutable [ 0 ] . StrProp ) ;
56+ }
57+
58+ public static void RefCopy_Test ( )
59+ {
60+ var list = new List < RefType > ( [ new RefType ( ) , new RefType ( ) , new RefType ( ) , new RefType ( ) ] ) ;
61+
62+ var readOnly = list . AsReadOnly ( ) ;
63+ var immutable = list . ToImmutableList ( ) ;
64+
65+ list . Add ( new RefType ( ) ) ;
66+ Console . WriteLine ( readOnly . Count ) ; // 5
67+ Console . WriteLine ( immutable . Count ) ; // 4
68+
69+ var newList = immutable . Add ( new RefType ( ) ) ;
70+ Console . WriteLine ( immutable . Count ) ; // 4
71+ Console . WriteLine ( newList . Count ) ; // 5
72+ }
73+
74+ public static void RefRoType_Test ( )
75+ {
76+ var list = new List < RefRoType > ( [ new RefRoType ( ) , new RefRoType ( ) , new RefRoType ( ) , new RefRoType ( ) ] ) ;
77+
78+ var readOnly = list . AsReadOnly ( ) ;
79+ var immutable = list . ToImmutableList ( ) ;
80+
81+ //immutable[0].StrProp = "abc"; //CS8852 Init-only property or indexer 'RefRoType.StrProp' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
82+ //immutable[0] = immutable[0] with { StrProp = "abc" }; //CS0200 Property or indexer 'ImmutableList<RefRoType>.this[int]' cannot be assigned to -- it is read only
83+ }
84+
4485 public static void Test ( )
4586 {
4687 var list = new List < int > ( ) ;
@@ -59,3 +100,28 @@ public static void Test()
59100 #endregion
60101
61102}
103+
104+ public class RefType
105+ {
106+ public RefType ( )
107+ {
108+ IntProp = 42 ;
109+ StrProp = "Hello, World!" ;
110+ }
111+
112+ #region Properties
113+
114+ public int IntProp { get ; set ; }
115+
116+ public string StrProp { get ; set ; }
117+
118+ #endregion
119+
120+ }
121+
122+ public record RefRoType ( int IntProp , string StrProp )
123+ {
124+ public RefRoType ( ) : this ( 42 , "RefRoType" )
125+ {
126+ }
127+ }
0 commit comments