二者没区别,前者是后者的简写而已。如果对取值或赋值有要求,那么只能用第二种。
例一:
1
2
3
4
5
6
7
8
9
10
11
|
private
int
_age;
public
int
Age
{
get
{
return
_age; }
set
{
if
(value < 1 || value > 120)
throw
new
System.ArgumentException(
"年龄只能在1-120范围内。"
);
_age = value;
}
}
|
例二:
1
2
3
4
5
6
7
8
9
10
|
private
List<
string
> _nameList;
public
List<
string
> NameList
{
get
{
if
(_nameList ==
null
)
_nameList =
new
List<
string
>();
return
_nameList;
}
}
|