基础【属性】-----(静态属性)------(转)
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Person person = new Person("001", "Allan", "男", 23, "软件工程师"); 6 Person person2 = new Person("002", "Angelina", "女", 23, "销售经理"); 7 Console.WriteLine("{0}, {1}, {2}, {3}, {4}", person.ID, person.Name, person.Gender, person.Age, person.post.Name); 8 Console.WriteLine("{0}, {1}, {2}, {3}, {4}", person2.ID, person2.Name, person2.Gender, person2.Age, person2.post.Name); 9 Console.ReadKey(); 10 } 11 } 12 13 class Person 14 { 15 public Person() { } 16 public Person(string id, string name, string gender, int age, string postName) 17 { 18 ID = id; 19 Name = name; 20 Gender = gender; 21 Age = age; 22 post.Name = postName; 23 } 24 public string ID { get; set; } 25 public string Name { get; set; } 26 public string Gender { get; set; } 27 public int Age { get; set; } 28 29 private static Post _post = null; 30 public Post post 31 { 32 get 33 { 34 if (_post == null) 35 _post = new Post(); 36 return _post; 37 } 38 } 39 } 40 41 /// <summary> 42 /// 职务 43 /// </summary> 44 class Post 45 { 46 public string ID { get; set; } 47 public string Name { get; set; } 48 }
整个的流程:
首先由Main入囗函数进入,执行到
Person person = new Person("001", "Allan", "男", 23, "软件工程师");
然后调用Person类的构造函数
1 public Person(string id, string name, string gender, int age, string postName) 2 { 3 ID = id; 4 Name = name; 5 Gender = gender; 6 Age = age; 7 post.Name = postName; 8 }
执行到黄色背景时,进入
1 public Post post 2 { 3 get 4 { 5 if (_post == null) 6 _post = new Post(); 7 return _post; 8 } 9 }
当然了,在进入Person时,会首先调用
private static Post _post = null;
到此为止,还是一切正常,没什么意外。我们看看内存中是什么样子:
当执行 private static Post _post = null 时,会在专为保存静态属性的内存开出一小段区域:

程序继续向下执行,判断_post是否为空,而后执行
_post = new Post();
这时在内存中一个叫做堆的地方开出一块内存

注:地址好像不是在这个位置上,只是个表示,大家理解就好。把这个地址1000赋予_post
_post那时的null就会变为1000

程序接着向下执行
Person person2 = new Person("002", "Angelina", "女", 23, "销售经理");
因为_post为静态属性,所以不会再执行
private static Post _post = null;
当程序执行到了
1 public Post post 2 { 3 get 4 { 5 if (_post == null) 6 _post = new Post(); 7 return _post; 8 } 9 }
就是这里,判断_post是否为空,因为_post是静态属性,所以一直持有这个对象,不会执行_post = new Post();
而是直接返回_post.
这样的话,在构造函数里面的
post.Name = postName;
post还是指向static区域里面的那个_post,它指向了地址为1000的那个对象,所以条语句是一个修改,既是把Name由原来的"软件工程师",改为了"销售经理"。
这也就不难理解下面的语句
1 Console.WriteLine("{0}, {1}, {2}, {3}, {4}", person.ID, person.Name, person.Gender, person.Age, person.post.Name);Console.WriteLine("{0}, {1}, {2}, {3}, {4}", person2.ID, person2.Name, person2.Gender, person2.Age, person2.post.Name);
里面的person.post.Name也为输出"销售经理"了。因为person.post和person2.person指向的是同一个区域。

浙公网安备 33010602011771号