C#对象初始化
C#对象初始化做了一些改进。一个新的功能就是提供了更方便的语法规则来声明变量的值。
假如我们声明一个Student对象:
publicclassStudent
{
privatestring_stuName;
privatestring_stuAge;
privateint_stuClass;
publicStudent(){}
publicstringStuName
{
get{return_stuName;}
set{_stuName=value;}
}
publicstringStuAge
{
get{return_stuAge;}
set{_stuAge=value;}
}
publicintStuClass
{
get{return_stuClass;}
set{_stuClass=value;}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
在C#2.0中,我们是这样声明变量并赋值的:
Studentstu=newStudent();
stu.StuName="Brian";
stu.StuAge="21";
stu.StuClass="1班";
- 1.
- 2.
- 3.
- 4.
而在C#3.0中,我们可以这样C#初始化对象:
Studentstu2=newStudent
{
StuName="Brian",
StuAge="21",
StuClass="1班"
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
从代码中不难看出,C#3.0给我们提供了很方便得方式来进行C#对象初始化工作。
【编辑推荐】