C#面向对象_封装_160922

来源:互联网 发布:软件标题修改器 编辑:程序博客网 时间:2024/06/05 21:15

public公共字段是可以被修改的

private是无法在类外访问

封装就是隐藏对象的信息,留出访问的接口

隐藏:private

属性:public

namespace OO
{
    class Child
    {

        //保护字段
        private string _sex;

        public string Sex//属性,变量名称首字母大写
        {
            get { return _sex; }//返回字段名,读访问器
            set { _sex = value; }//写访问器,如果没有set这个属性就是只读的
        }
        public void PlayBall()
        {
            Console.WriteLine("I am palying ball");
        }
    }
}

如何在对赋值进行限制(假如要限制年级,在set里面设置3-7岁)

namespace OO
{
    class Child
    {
        //保护字段
        private string _sex;

        public string Sex//属性,首字母大写
        {
            get { return _sex; }//返回字段名,读访问器
            set { _sex = value; }//写访问器
        }
        private int _age;
        public int Age
        {
            get { return _age; }
            set
            {
                if (value >= 3 && value <= 7)
                    _age = value;
            }
        }
        public void PlayBall()
        {
            Console.WriteLine("I am palying ball");
        }
    }
}

//进来看主函数,即使设置为80岁,也不会输出!!!这就是条件结构起作用了!!

namespace OO
{
    class Program
    {
        static void Main(string[] args)
        {
            Child xiaoMing = new Child();//实例化
            xiaoMing.Sex = "boy";//大写S
            xiaoMing.Age = 5;
            xiaoMing.Age = 80;
 
            Console.WriteLine("sex= {0}, age = {1}", xiaoMing.Sex,xiaoMing.Age);
            //xiaoMing.PlayBall();
        }
    }
}


0 0
原创粉丝点击