技术开发 频道

c#3.0系列:Automatic Property


【IT168技术文档】

  之前的做法:
  在c#3.x出来之前,相信大家已经习惯通过一个private field + public property的发式来定义和实现一个public Property。就如下面方式实现。
1class person 2 { 3 private int age; 4 private string _name; 5 public int Age 6 { 7 get { return age; } 8 set { age = value; } 9 } 10 public string Name 11 { 12 get { return _name; } 13 set { _name = value; } 14 } 15 }
  显然你可以在Property中的set/get代码块中,我们可以不受限制地定义我们的业务逻辑,但是在大多是场合下,我们都是像上面的code一样直接对一个定义的field进行操作:对其读写。但是我们如果根据项目的需要,例如作为Business Entity的Class,需要封装非常多的数据,我们需要为不同类型的数据分别定义一个Property,这样不断重复的工作大家一定觉得很厌烦。
  Automatic Property Overview
  在c#3.x出来之后,我们可以通过Automatic Property来简化我们的操作。例如:
1class Employee 2 { 3 //public string Name { get; } error 4 public string Name { get; set; } 5 public int Age{get; private set;} 6 public Employee(string name,int age ) 7 { 8 this.Name = name; 9 this.Age = age; 10 } 11 }
  上面的好处我就不用说了。
  Automatic Property IN CLR
  首先让我们看看c#3.x出来之前和出来之后,编译器是怎么处理的:
0
相关文章