search
HomeBackend DevelopmentC#.Net TutorialC# basic knowledge compilation: basic knowledge (2) category

Classes are the basis of object-oriented languages. The three major characteristics of classes: encapsulation, inheritance, and polymorphism. The most basic feature is encapsulation.
Programmers use programs to describe the world and regard everything in the world as objects. How to describe this object? That's the class. That is, classes are used to encapsulate objects. In book terms, a class is an abstraction of objects with the same properties and behavior. BMW cars, Buick cars, Wuling Zhiguang cars... basically have the same attributes and behaviors, so you can abstract a car class. Of course, you can also abstract the BMW car of passerby A and the Buick car of passerby B... Abstract a car class .
After the class abstraction is completed, it can be instantiated. After instantiation, it is called an object, and then you can assign values ​​to properties or run methods of the class. Properties and methods are associated with each object. Different objects have the same properties, but the property values ​​may be different; they also have the same methods, but the results of the method execution may be different.
The attributes and methods of a class are encapsulated by the class.
Look at the definition of the following class:

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();
        }
    }
}

Result:

The above is the basic knowledge of C#: the content of basic knowledge (2) class, more For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)