Understand C # reference type,
A Bug occurred in the project due to insufficient understanding of the reference type.
First, sort out C # basics: The reference type value assignment assigns the object pointer, while the value type value assignment is the copy, which is one of the differences between the reference type and the value type.
Code:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 var obj = MyClassA.PropertyA; 6 Console.WriteLine(string.Join(",", MyClassA.PropertyA.Foo)); 7 obj.Foo.RemoveAll(m => m == "e"); 8 Console.WriteLine(string.Join(",",MyClassA.PropertyA.Foo)); 9 10 Console.WriteLine(string.Join(",",MyClassA.PropertyA.Bar));11 obj.Bar = obj.Bar.Where(m => m > 2).ToList();12 Console.WriteLine(string.Join(",", MyClassA.PropertyA.Bar));13 14 obj.Foo = new List<string> {"x", "y", "z"};15 Console.WriteLine(string.Join(",", MyClassA.PropertyA.Foo));16 17 Console.Read();18 }19 }20 class MyClassA21 {22 static MyClassA()23 {24 PropertyA=new MyClassB();25 PropertyA.Foo = new List<string> { "a", "b", "c", "d","e"};26 PropertyA.Bar = new List<int> {1, 2, 3, 4, 5};27 }28 public static MyClassB PropertyA { get; private set; }29 }30 31 class MyClassB32 {33 public List<string> Foo { get; set; }34 public List<int> Bar { get; set; }35 }
It is hard to understand: I clearly operate on the internal members of obj. Why is the value of MyClassA. PropertyA changed?
Because, when MyClassA. PropertyA is assigned to obj, obj points to MyClassA (reference type). Therefore, as long as the object is operated on, it is actually an internal Member of MyCalssA.