











之前的做法:
在c#3.x出来之前,相信大家已经习惯通过一个private field + public property的发式来定义和实现一个public Property。就如下面方式实现。
1
class 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
}
1
class 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
}
internal class Employee
{
// Fields
[CompilerGenerated]
private int <Age>k__BackingField;
[CompilerGenerated]
private string <Name>k__BackingField;

// Methods
public Employee(string name, int age);

// Properties
public int Age { get; private set; }
public string Name { get; set; }
}


abstract class people
{
public abstract string Name { get; set; }
public abstract int Age { get; set; }
}
不能定义只读或者只写的属性,必须同时提供
请看上面Employee。第一行,编译器会报错。
可以给读和写赋予不同的访问权限
请看上面
Employee。Age属性,请注意他的操作权限。
自动属性的初始化
动属性会为字段自动赋予变量类型的初始值,如果是引用类型,则为null,如果你想初始化,必须要在
自定义的构造函数初始化。请看上面
Employee。
不适用的情况
果想在属性中增加判断、验证等逻辑,则只能用传统的属性定义方法实现 如下:
1
public int Age
2
{
3
get { return age; }
4
set
5
{
6
if ((value > 0) && (value < 500))
7
{
8
age = value;
9
}
10
else
11
{
12
throw new ArgumentOutOfRangeException ("你不是人!");
13
}
14
}
15
}
16
版权所有归"布衣软件工作者".未经容许不得转载.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。