属性的作用就是保护字段,对字段的赋值和取值进行设定
语法:public 数据类型 属性名{
get{return _name;}//当你对属性取值的时候,先执行get方法
set{_name=value;}//当你给属性赋值的时候,先执行set方法
}
属性的本质:属性的本质就是两个方法,一个get方法,一个set方法
字段是私有的(private),是被保护的。默认
private(私有的):只能在当前类的内部访问,出了这个类就访问不到了。
例子:
//创建一个类
public class Person()
{
string _name;//字段是私有的
public string Name{
get{return _name;}
set{_name=value;}
}
int _age;
public int Age{
get{return _age;}
set{
if(value<0||value>100){ //对年龄进行限定
value=0;
}
_age=value;}
}
char _gender;
public char Gender{
get{
if(_gender!='男'||_gender!='女'){
return '男';
}
return _gender;}
set{_gender=value;}
}
public void Run() //非静态方法
{
Console.WriteLine("我叫{0},我今年{1}岁了,我是一名{2}生",this.Name,this.Age,this.Gender);
}
}
Main()函数:
public static void Main()
{
Person xiaoCai=new Person();
xiaoCai.Name="小菜";
xiaoCai.Age=-24;//赋的值不符合规范
xiaoCai.Gender="中";
}