namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
Student stu1 = new Student();
stu1.SetAge(20);
Student stu2 = new Student();
stu2.SetAge(20);
Student stu3 = new Student();
stu3.SetAge(20);
int avgAge = (stu1.GetAge() + stu2.GetAge() + stu3.GetAge()) / 3;
Console.WriteLine(avgAge);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class Student
{
private int age;
public int GetAge()
{
return this.age;
}
public void SetAge(int value)
{
if (value >= 0 && value <= 120)
{
this.age = value;
}
else
{
throw new Exception("Age参数范围错误");
}
}
}
}
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
Student stu1 = new Student();
stu1.Age = 20;
Student stu2 = new Student();
stu2.Age = 20;
Student stu3 = new Student();
stu3.Age = 20;
int avgAge = (stu1.Age + stu2.Age + stu3.Age) / 3;
Console.WriteLine(avgAge);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class Student
{
private int age;
public int Age
{
// 访问器
get
{
return this.age;
}
set
{
// 上下文关键字 value
if (value >= 0 && value <= 120)
{
this.age = value;
}
else
{
throw new Exception("Age参数范围错误");
}
}
}
}
}
快速生成完成属性
visual Studio快速生成属性
在类中,输入propfull
,接着按2下tab
键
class Student
{
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
}
简略声明
visual Studio快速生成属性
在类中,输入prop
,接着按2下tab
键
class Student
{
public int Age { get; set; }
}
私有set,只能在类中进行赋值
class Student
{
private int age;
public int Age
{
get { return age; }
// 只能在类中进行赋值
private set { age = value; }
}
public void say()
{
this.Age = 200;
}
}
练习
Age满足16岁可以工作,调用CanWork判断是否满足条件
每次访问CanWork时,计算age是否满足要求
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
Student stu = new Student();
stu.Age = 16;
Console.WriteLine(stu.CanWork);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class Student
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public bool CanWork
{
get
{
if (this.age >= 16)
{
return true;
}
else
{
return false;
}
}
}
}
}
在setAge时,计算age是否满足要求
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
Student stu = new Student();
stu.Age = 16;
Console.WriteLine(stu.CanWork);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class Student
{
private int age;
public int Age
{
get { return age; }
set
{
age = value;
// 每次赋值后都调用CalculateCanWork()进行判断
this.CalculateCanWork();
}
}
private bool canWork;
public bool CanWork
{
get
{
return canWork;
}
}
private void CalculateCanWork()
{
if (this.age >= 16)
{
this.canWork = true;
}
else
{
this.canWork = false;
}
}
}
}