Object and type (structure, weak reference, extension method), reference Extension
1 public class Program1 2 {3 # region structure 4 // The structure is a value type and stored on the stack 5 // 1: The member variables in the structure cannot have an initial value 6 // 2: the non-argument constructor 7 struct Example 8 {9 // public int Width = 1; // error 10 // public int Height = 1; // error 11 12 public int Width; // correct 13 public int Height; // correct 14 15 // error 16 // public Example () 17 // {18 19 //} 20 21 // correct 22 public Example (int width, int height) 23 {24 Width = width; 25 Height = height; 26} 27} 28 # endregion29}
Structure
1 public class Program1 2 {3 public class MyClass 4 {5 public int value {get; set;} 6} 7 8 static void Main (string [] args) 9 {10 // generally, the garbage collector does not clean up the object's memory 11 // MyClass myClass = new MyClass (); // this declaration is a strong reference 12 13 # region weak reference 14 // when the weak reference is instantiated, the Garbage Collector may recycle the object and release the memory 15 // so it is used, you need to determine whether the application exists 16 17 WeakReference reference = new WeakReference (new MyClass (); 18 19 MyClass myClass = reference. target as MyClass; 2 0 21 if (myClass! = Null) 22 {23 myClass. value = 10; 24 25 Console. writeLine (myClass. value); 26} 27 28 // reclaim 29 GC. collect (); 30 31 if (reference. isAlive) 32 {33 myClass = reference. target as MyClass; 34 35 myClass. value = 1; 36 37 Console. writeLine (myClass. value); 38} 39 else40 {41 Console. writeLine ("reference does not exist"); 42} 43 44 # endregion45 46} 47} 48}
Weak reference
1 public class Program1 2 {3 public class MyClass 4 {5 public int Value {get; set ;} 6} 7 8 # region Extension Method 9 10 /// <summary> 11 // MyClass extension method; the extension method must be static. If the extension method has the same name as the original method, 12 // give priority to calling the original method; note this13 /// </summary> 14 public static class MyClassExtension15 {16 public static int GetValue (this MyClass myClass, int addValue) 17 {18 return myClass. value + addValue; 19} 20 21} 22 23 # endregion24}
Extension Method