代码如下
using System.Runtime.CompilerServices;
namespace _02_属性与private
{
internal class Program
{
static void Main(string[] args)
{
Student stu1 = new Student(); //已经无法找到Student.age
Student stu2 = new Student();
//Student stu3 = new Student() {Age = 200 }; //这样写运行后就会直接报错,程序崩溃,所以需要放到try中
try
{
Student stu3 = new Student() { Age = 200 }; //运行到这里后,下面的两个set都没有运行
stu1.SetAge(20);
stu2.SetAge(200);
}
catch(Exception ex)
{
try
{
Student.Amount = -200;
}
catch(Exception ex1)
{
Console.Write(ex1.Message);
}
Console.WriteLine("");
Console.Write(ex.Message);
}
int averageAge = (stu1.GetAge() + stu2.GetAge())/ 2;
Console.WriteLine("");
Console.WriteLine(averageAge);
Console.WriteLine("");
Console.WriteLine("以下体现动态计算====================================================================");
Student stu4 = new Student() {Age = 14};
Console.WriteLine(stu4.CanWork); //注意:这里Console.WriteLine(stu4.CanWork());是错误的写法
}
}
class Student
{
private int age;
public int GetAge() //不能是static 这里是采用函数做参数引用,知道原理
{
return this.age;
}
public void SetAge(int age)
{
if (age >= 0 && age <= 120)
this.age = age;
else
throw new Exception("Age value has error");
}
public int Age //对private int age 进行定义属性
{
get { return this.age; }
set
{
if (value >= 0 && value <= 120) //自动创建默认的value参数,根据上下文自动设定数型
this.age = value;
else
throw new Exception("No2. Age value has error");
}
}
private static int amount;
public static int Amount //对amount设定属性,做安全限制
{
get { return amount; }
set
{
if (value >= 0)
{
Student.amount = value;
}
else
throw new Exception("amount value is Error");
}
}
public bool CanWork
{
get
{
if (this.age >= 16) return true;
else return false;
}
}
}
}
结果
还有一种方式更为便捷的采用private在设定变量的时候直接检测,有待后期仔细研究