C#学习-属性与private

代码如下

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在设定变量的时候直接检测,有待后期仔细研究

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值