>  기사  >  백엔드 개발  >  C# 기초지식 편찬: 기초지식(2) 카테고리

C# 기초지식 편찬: 기초지식(2) 카테고리

黄舟
黄舟원래의
2017-02-10 15:36:571356검색

클래스는 객체지향 언어의 기초입니다. 클래스의 세 가지 주요 특징: 캡슐화, 상속, 다형성. 가장 기본적인 기능은 캡슐화입니다.
프로그래머는 프로그램을 사용하여 세상을 설명하고 세상의 모든 것을 객체로 간주합니다. 그게 수업이에요. 즉, 클래스는 객체를 캡슐화하는 데 사용됩니다. 책에서 클래스는 동일한 속성과 동작을 가진 객체의 추상화입니다. BMW 자동차, 뷰익 자동차, 무릉지광 자동차... 기본적으로 동일한 속성과 동작을 가지므로 자동차 클래스를 추상화할 수 있음은 물론, 통행인 A의 BMW 자동차와 통행인 B의 뷰익 자동차도 추상화할 수 있습니다. .자동차 클래스를 추상화합니다.
클래스 추상화가 완료된 후 인스턴스화할 수 있으며, 인스턴스화한 후 객체라고 하며, 그 후 클래스의 속성에 값을 할당하거나 클래스의 메서드를 실행할 수 있습니다. 속성과 메서드는 각 개체와 연관되어 있습니다. 서로 다른 개체는 동일한 속성을 갖지만 속성 값은 다를 수 있지만 메서드 실행 결과는 다를 수 있습니다.
클래스의 속성과 메서드는 클래스에 의해 캡슐화됩니다.
다음 클래스의 정의를 보세요:

using System;

namespace YYS.CSharpStudy.MainConsole
{
    /// <summary>
    /// 定义一个学校类
    /// 这个类只有属性,没有方法(其实确切的来说是有一个默认的构造器方法)
    /// </summary>
    public class YSchool
    {
        /// <summary>
        ///字段, 类里面定义的变量称之为“字段”
        /// 保存学校的ID
        /// </summary>
        private int id = 0;

        /// <summary>
        /// 保存学校的名字
        /// </summary>
        private string name = string.Empty;

        /// <summary>
        /// 属性,字段作为保存属性值的变量,而属性则有特殊的“行为”。
        /// 使用get/set来表示属性的行为。get取属性值,set给属性赋值。因此get/set称为“访问器”。
        /// 
        /// ID属性
        /// </summary>
        public int ID
        {
            get
            {
                //get返回一个值,表示当前对象的该属性的属性值。
                return this.id;
            }
            //这里的.号用于访问对象的属性或方法。
            //this指当前对象,意即哪个实例在操作属性和方法,this就指哪个实例。
            set
            {
                //局部变量value,value值是用于外部赋给该该属性的值。
                this.id = value;
            }
        }
        /// <summary>
        /// 姓名属性
        /// </summary>
        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                name = value;
            }
        }
    }

    public class YTeacher
    {
        private int id = 0;

        private string name = string.Empty;

        //这里将YSchool类作为了YTeacher的一个属性。
        private YSchool school = null;

        private string introDuction = string.Empty;

        private string imagePath = string.Empty;

        public int ID
        {
            get
            {
                return id;
            }

            set
            {
                id = value;
            }
        }

        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                name = value;
            }
        }

        public YSchool School
        {
            get
            {
                if (school == null)
                {
                    school = new YSchool();
                }
                return school;
            }

            set
            {
                school = value;
            }
        }

        public string IntroDuction
        {
            get
            {
                return introDuction;
            }

            set
            {
                introDuction = value;
            }
        }

        public string ImagePath
        {
            get
            {
                return imagePath;
            }

            set
            {
                imagePath = value;
            }
        }

        /// <summary>
        /// 给学生讲课的方法
        /// </summary>
        public void ToTeachStudents()
        {
            //{0},{1},{2}是占位符,对应后面的参数。一般如果显示的内容中含有参数,我比较喜欢用string.Format。
            Console.WriteLine(string.Format(@"{0} 老师教育同学们: Good Good Study,Day Day Up!", this.name));
        }
        /// <summary>
        /// 惩罚犯错误学生的方法
        /// </summary>
        /// <param name="punishmentContent"></param>
        public void PunishmentStudents(string punishmentContent)
        {
            Console.WriteLine(string.Format(@"{0} 的{1} 老师让犯错误的学生 {2}", this.school.Name, this.name, punishmentContent));
        }

        //字段、属性和方法前修饰符有:public,private,protected,internal
        //public,字段、属性和方法均为公开的,不仅类中的其它成员能访问到,还可以通过类的实例访问的到。
        //private,字段、属性和方法均为私有的,只能被类中的其它成员访问到,不能通过类的实例访问。
        //protected,包含private特性,而且protected修饰的字段、属性和方法能被子类访问到。
        //internal,在同一个程序集中和public一样,但是不能被其它程序集访问,而且子类的话,只能被同一个命名空间的子类访问到。
    }
}
using System;

namespace YYS.CSharpStudy.MainConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化具体对象,并且赋值
            YSchool shool1 = new YSchool();

            shool1.ID = 1;

            shool1.Name = "清华附中";

            YSchool school2 = new YSchool();

            school2.ID = 2;

            school2.Name = "北师大附中";

            YTeacher techerS = new YTeacher();

            techerS.ID = 1;

            techerS.Name = @"尚进";

            techerS.School = shool1;

            techerS.IntroDuction = @"很严厉";

            techerS.ImagePath = @"http://";

            //运行当前实例的方法
            techerS.ToTeachStudents();

            //运行当前实例的方法,传入参数
            techerS.PunishmentStudents(@"抄所有学过的唐诗一百遍");

            Console.WriteLine();

            YTeacher techerQ = new YTeacher();

            techerQ.ID = 2;

            techerQ.Name = @"秦奋";

            techerQ.School = school2;

            techerQ.IntroDuction = @"和蔼可亲";

            techerQ.ImagePath = @"http://";

            techerQ.ToTeachStudents();

            techerQ.PunishmentStudents(@"抄所有学过的数学公式一遍");

            Console.ReadKey();
        }
    }
}

결과:

위는 C#의 기본 지식을 요약한 것입니다. 기본 지식( 2) 수업 내용, 기타 자세한 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.