Chapter 8. 面向对象(封装)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 封装
{
    public class Person
    {
        //字段:存储数据
        string _name;   //类中的成员,如果不加访问修饰符,默认private
        int _age;
        char _gender;


        //属性:保护字段,对字段的取值和设置进行限定(get()和 set())
        public string Name
        {
            get { return _name; }

            set                          
            {
                if ( value != "John")     //在set中限定(姓名)
                {
                    value="John";
                }
                _name = value; 
            }
        }

        public int Age
        {  
            get 
            {
                if (_age < 0 || _age > 100)    //在get中限定(年龄)
                {
                    return _age=0;
                }
                return _age; 
            }

            set { _age = value; }
        }

        public char Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }



        //方法:描述对象的行为

        //实例方法:
        public void SayHello()
        {
            string Name = "Lucy";
            int Age = 20;
            char Gender = '';

            //this作用1:代表当前类的对象
            Console.WriteLine("{0},{1},{2}", this.Name, this.Age, this.Gender);
            Console.WriteLine("{0},{1},{2}", Name, Age, Gender);
        }

        //静态方法:
        public static void SayHello2()
        {
            Console.WriteLine("Hello 我是静态的");
        }

        /* 构造函数:
         * 初始化对象(给对象的每个属性依次赋值)
         * 1、没有返回值,void也没有
         * 2、构造函数的名称跟类名一样
         */

        public Person(string name, int age, char gender)
        {
            this.Name = name;
            this.Age = age;

            if (gender != '' && gender != '')  //在构造函数中限定(性别)
            {
                gender = '';
            }
            this.Gender = gender;
        }

        //this作用2:调用当前类的构造函数
        public Person(string name,char gender):this(name,0,gender)
        { 
                
        }
    } 
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 封装
{
    class Program
    {
        static void Main(string[] args)
        {
             /*
             * new:
             * 1、在内存中开辟一块空间
             * 2、在开辟的空间中创建对象
             * 3、调用对象的构造函数
             */

            //调用非静态的方法:(先要实例化对象)
            Person zsPerson = new Person("张三",-19,'');
            zsPerson.SayHello();

            //调用静态的方法:(类名.方法名)
            Person.SayHello2();

            Console.ReadLine();
        }
    }
}

posted @ 2016-06-17 14:33  庚xiao午  阅读(149)  评论(0编辑  收藏  举报