C#笔记——字段和属性
关于字段和属性的区别:
- 字段在对象内部保存,因此尽量用private或者protect修饰符
- 属性是字段的对外展示和对内的通道,通过属性来对值进行取出或者设置
- 好处是:属性对字段进行了一层包装,避免直接访问到字段,在进行赋值的时候可以进行一下异常验证
class Program
{
static void Main(string[] args)
{
try
{
Student stu1 = new Student();
stu1.Age = 20;
Student stu2 = new Student();
stu2.Age = 30;
Student stu3 = new Student();
stu3.Age = 40;//若此处被赋值为大于120的数值,那么就会抛出异常
int average = (stu1.Age + stu2.Age + stu3.Age) / 3;
Console.WriteLine(average);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
class Student
{
//age字段
private int age;
//Age属性
public int Age
{
get
{
return age;
}
set
{
if (value > 0 && value <= 120)
{
this.age = value;
}
else
{
throw new Exception("输入的数据有误!");
}
}
}
}