对象和类型(结构、弱引用、扩展方法)

2018-06-17 19:06:33来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 1 public class Program1
 2     {
 3         #region 结构
 4         //结构是值类型,存储在栈上
 5         //1:结构中的成员变量不能有初始值
 6         //2:结构中不能声明无参数构造函数
 7         struct Example
 8         {
 9             //public int Width = 1;//错误
10             //public int Height = 1;//错误
11 
12             public int Width;//正确
13             public int Height;//正确
14 
15             //错误
16             //public Example()
17             //{
18 
19             //}
20 
21             //正确
22             public Example(int width, int height)
23             {
24                 Width = width;
25                 Height = height;
26             }
27         }
28         #endregion
29 }
结构
 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             //一般实例化类型的时候,垃圾回收器一般不会清理对象的内存
11             //MyClass myClass = new MyClass();//这种声明属于强引用
12 
13             #region 弱引用
14             //弱引用实例化的时候,垃圾回收器可能会回收掉对象释放内存
15             //所以使用的时候,需要判断应用是否存在
16 
17             WeakReference reference = new WeakReference(new MyClass());
18 
19             MyClass myClass = reference.Target as MyClass;
20 
21             if (myClass != null)
22             {
23                 myClass.value = 10;
24 
25                 Console.WriteLine(myClass.value);
26             }
27 
28             //回收
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             else
40             {
41                 Console.WriteLine("引用不存在");
42             }
43             
44             #endregion
45             
46         }
47     }    
48 }
弱引用
 1 public class Program1
 2 {
 3     public class MyClass
 4     {
 5         public int Value { get; set; }
 6     }
 7 
 8     #region 扩展方法
 9 
10     /// <summary>
11     /// MyClass的扩展方法;扩展方法必须是静态的,如果扩展方法与原方法重名,
12     /// 优先调用原方法;注意this
13     /// </summary>
14     public static class MyClassExtension
15     {
16         public static int GetValue(this MyClass myClass, int addValue)
17         {
18             return myClass.Value + addValue;
19         }
20 
21     }
22 
23     #endregion
24 }
扩展方法

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:访问修饰符

下一篇:对象和类型(数组、ref、out)