C#面向对象基础(三) 属性
为Animal类加一个字段 weight 动物的体重
public int weight;
为了能访问值,当然是public. public , 会带来可怕的后果
myFarm.goat.weight = 100;
myFarm.goat.weight = -100;
myFarm.goat.weight = -100;
羊羊的体重 100 直接变到-100 -100都行?! 这是不能接受的! 将weight改为private
为了对weight值访问,加入两个方法.
public void setWeight(int w)
{
if (w > 0)
{
weight = w;
}
}
public int getWeight()
{
return weight;
}
{
if (w > 0)
{
weight = w;
}
}
public int getWeight()
{
return weight;
}
在setWeight方法中,体重必须是>0 才有效.
这样,太麻烦咯.这时,应该用"属性"
private int weight;
public int Weight
{
get{return weight;}
set { if (value > 0) weight = value; }
}
public int Weight
{
get{return weight;}
set { if (value > 0) weight = value; }
}
属性的使用
myFarm.goat.Weight = 100;//set value =100
Console.WriteLine(myFarm.goat.Weight); //get
Console.WriteLine(myFarm.goat.Weight); //get