[Full stack plan - C# of programming language] Understand the class and hold the object

foreword

insert image description here
Now the more popular argument is: object-oriented refers to the programming of everything as an object to describe. At the same time, object orientation enhances the code 重用性.

I think it's good to hear a concept. At this stage, understanding them is not very helpful for us to write code~

The following objects include content that needs attention

对象包括属性和方法, properties refer to the inherent characteristics of the object, and methods are the behavior of the object.

Think of a cell phone as an object, for example.
The size, color, and brand of the mobile phone can be regarded as a feature ====> attribute ;
while calling, sending text messages, and surfing the Internet are the behaviors ====> methods of the mobile phone .

insert image description here

Mind map of this article

insert image description here

insert image description here

kind

The three major characteristics of object-oriented languages ​​- encapsulation, inheritance, and polymorphism can be well reflected through classes.

[1], the definition of class

The syntax for a class definition is as follows:

类的访问修饰符 修饰符 类名
{
    
    
	类的成员
}
① Class access modifiers - used to set access restrictions on classes

类的访问修饰符有2个
1) public: this class can be accessed in any project
2) internal/do not write: this class can only be accessed in the current project
insert image description here

② Modifier - a description of the characteristics of the class itself

including abstract, sealed and static
insert image description here

③ Class name

The class name is similar to the conventional variable name. Generally, when naming, it is best to express the function of the class. Class names must be unique within the same namespace.

④ Class members - elements that can be defined in a class

Mainly include fields, properties, methods

insert image description here

[two], the members of the class

Members of the class include 字段, 属性, 方法. Each class member needs to specify access modifiers and modifiers when it is defined.

Generic - Access Modifiers

There are 4 access modifiers for members in a class

1) public - members can be accessed by any code
2) private - members can only be accessed by code within the same class

If no modifier is used before the class member, it defaults to private

3) internal - members can only be accessed by code in the same project
4) protected - members can only be accessed by code in the class or derived class

Derived classes are involved in inheritance

Members of a class - fields and properties

字段The definition of is similar to the definition of variables and constants, except that access modifiers and modifiers can be added in front of variables or constants.

The syntax of the definition 字段is as follows:

访问修饰符 修饰符 数据类型 字段名;

field modifier

Two modifiers are usually used when modifying fields, namely readonly (read-only) and static (static)

1) readonly - can only read the value of the field and cannot assign a value to the field
insert image description here

2) static - static fields, which can be accessed directly through the class name

注意常量不能使用static修饰符 修饰

get accessor and set accessor

Properties are often used in conjunction with fields, and provide get and set accessors to get or set the field's value, respectively.

知识普及一:
The use of get accessor and set accessor is actually quite similar to the use of methods. When operating a field, you can set the value of the acquired field according to some rules and conditions.

知识普及二:
Optionally remove get accessors or set accessors.

1) The get{}
get accessor is used to set the value of the acquired property. At the end, you need to use return to return a value compatible with the data type of the property.

If the accessor is omitted in the property definition, the field value of the private type cannot be obtained in other classes, so it is sometimes called a write-only property

2) set{}
The set accessor is used to set the value of the field. Here you need to use a special value value, which is used to assign a value to the field.

After the set accessor is omitted, the field cannot be assigned a value in other classes, so it is also called a read-only property.


① Property settings:
Syntax:

public    数据类型    属性名
{
    
    
    get
    {
    
    
        获取属性的语句块;
        return;
    }
    set
    {
    
    
        设置属性得到语句块;
    }
}

Tips: Because properties are assigned to a field , properties are usually named by capitalizing the first letter of each word in the field. For example, a field named name is defined, and the attribute name is Name.


[Walking through the classroom] Define a book information class (Book), define three fields of book number (id), book name (name), and book price (price) in the class, and set attributes for these three fields respectively, among which Set the book name to read-only property.

Reference Code

using System;

namespace OOPDemo_1
{
    
    
    class Book
    {
    
    
        private int id;
        private string name;
        private double price;
        //设置图书编号属性
        public int Id
        {
    
    
            get
            {
    
    
                return id;
            }
            set
            {
    
    
                id = value;
            }
        }
        //设置图书名称属性
        //根据要求,将图书的书名设置为只读属性
        public string Name
        {
    
    
            get
            {
    
    
                return name;
            }
        }
        //设置图书价格属性
        public double Price
        {
    
    
            get
            {
    
    
                return price;
            }
            set
            {
    
    
                price = value;
            }
        }
    }
}

② Automatic property setting
Definition syntax:

public    数据类型    属性名{
    
    get;set;}

Reference Code

public int Id{
    
    get; set;}
public string Name{
    
    get; set;}
public double Price{
    
    get; set;}

This code is indeed a lot simpler.
insert image description here

Use Note 1:
If you use the method to set the property, you do not need to specify the field in自动属性设置 the curly bracketsBut if you want to set a property as a read-only property, you can simply omit the set accessor.

public int Id{
    
    get;}

If you still want to assign a value to an attribute at this time, you can do this

//只读属性
public int Id{
    
    get;}=1//常规
public int Id{
    
    get; set;}=1;

insert image description here

Use note two:

The method of automatically generating properties cannot omit the get accessor . If other classes are not allowed to access the property value, it can be achieved by addingprivatemodifiers.

public int Id{private get; set;}

Members of a class - methods

conventional approach

The main method Main() is the entry and exit of the execution program

A method is a way of putting together the contents that complete the same function, which is convenient for writing and calling. Also reflected in object-oriented languages 封装性.

Syntax for defining a method:

访问修饰符    修饰符    返回值类型    方法名(参数列表)
{
    
    
    语句块;
}

1) Access modifiers

All access modifiers that modify class members can also be used to modify methods. If omitted and not written, the default is private
2) Modifier
insert image description here

3) Return value type

It is used to get the return result after calling the method. The return value can be any data type. If the return value type is specified, the return keyword must be used to return a value that matches the type.
If no return value type is specified, the void keyword must be used to indicate no return value.
4) Method name

The method name is named according to the Pascal nomenclature. Duplicate names are supported because there are方法的重载

insert image description here

5) Parameter list

0 or more parameters are allowed in the method. If no parameters are specified, the parentheses of the parameter list are preserved.
The definition form of parameters is 数据类型 参数名that if multiple parameters are used, they need to be separated by a 逗号comma.
insert image description here

Construction method

① The name of the constructor is the same as the name of the class

Creating an object of a class is done using 类名 对象名 = new 类名()the method.
In fact, 类名()the form here calls类的构造方法

For object creation, if there is no custom constructor in the new class, a default constructor with no parameters generated by the system will be used.

② Definition syntax of constructor
访问修饰符  类名 (参数列表)
{
    
    
    语句块;
}

The access modifier of the constructor here is usually of public type , so that objects of this class can be created in other classes.
If the access modifier is set to private type, objects of this class cannot be created.

The parameters in the constructor are 0 or more parameters like other methods.

Tips: It is precisely because it can take parameters, so you can put some class member initialization operations into the constructor to complete, which can not only create objects, but also initialize objects

insert image description here

Deconstruction method

It is good to understand the destructor method, and the destructor method is used when garbage collecting and releasing resources.
It's a little far from us for a while. Accumulate first.

Defining method definition syntax

~类名()
{
    
    
    语句块;
}

Without any parameters in the destructor method, it guarantees that the garbage collection method Finalize() will be called in the program.

method overloading

When defining a constructor, you can define a constructor with 0 or more parameters, but the name of the constructor must be the class name.
In fact, this is a typical method overloading, that is, 方法名称相同、参数列表不同。
insert image description herewhen calling an overloaded method, the system judges which method to call based on the different parameters passed.


The overloading of methods is relatively easy to understand. I want to focus on expanding 方法参数the knowledge about

① Actual parameters and formal parameters
The parameters in the method are divided into actual parameters and formal parameters.
Actual parameters are called actual parameters and are 调用方法the parameters passed in;
formal parameters are called formal parameters and are the方法定义 parameters written in .

② Reference parameters and output parameters
In addition to defining data types, parameters in a method can also define reference parameters and output parameters.
Reference parameters are defined using the ref keyword;
output parameters are defined using the out keyword.

Two points to note:

1) When calling a method with a reference parameter, the actual parameter must be a variable, not a variable or an expression, etc., and the ref keyword must be added when passing a value.

When it is an expression, it will report an error:
insert image description here
when it is a constant, it will also report an error
insert image description here

2) When using output parameters, the reference parameters must be assigned to the output parameters before the method call is completed
. The parameters are similar to the parameters we usually use, but the output parameters are different. The output parameters are equivalent to the return value, that is, the returned value can be returned after the method call is completed. The result is stored in the output parameter.

Output parameters are mostly used when a method needs to return multiple values.
When using output parameters, you must use the out keyword when passing the parameter, but you do not have to assign a value to the output parameter; the output parameter is assigned a value
before the method call completes.
insert image description here

demo code

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

/*
 * 【实例 1】创建名为 RefClass 的类,
 * 在类中定义一个判断所输入整数是否为 5 的倍数的方法,
 * 并将方法中传入的整数参数定义为 ref 类型的。
 */
namespace OOPDemo_1
{
    
    
    class RefClass
    {
    
    
        public bool Judge(ref int num)
        {
    
    
            if ((num % 5) == 0) return true;
            else return false;
        }
    }
}

/*******************************************************/

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

/*
 * 【实例 2】创建一个 OutClass 类,在类中定义与【实例 1】类似的方法,
 * 只是在方法的参 数中增加一个输出参数,用于返回判断的结果。
 */
namespace OOPDemo_1
{
    
    
    class OutClass
    {
    
    
        public void Judge(int num,out bool result)
        {
    
    
            if (num % 5 == 0) result = true;
            else result = false;
        }
    }
}

/*******************************************************/
using System;

namespace OOPDemo_1
{
    
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
         RefClass refClass = new RefClass();
            int a = 20;
            //int b = 23;
            //const int N = 5;
            //在调用带有引用参数的方法时,实际参数必须是一个变量,并且在传值时必须加上 ref 关键字。
            bool res = refClass.Judge(ref a);
            Console.WriteLine("验证结果是:" + res);

            //调用含有带输出参数的方法时,必须在传递参数时使用 out 关键字,但不必给输出参数赋值
            OutClass outClass = new OutClass();
            bool rs;
            outClass.Judge(a, out rs);
            Console.WriteLine(rs);
            }
        }
 }

call class member

Calling a member of a class requires using an object of this class, for creating an object of the class.

The syntax for creating a class object is as follows:

类名 对象名 = new 类名();

The syntactic form above is a simple form that invokes members of a class by 对象名combining . The syntax of the call is as follows:.运算符

对象名 . 类的成员

For the object of the class, my own understanding is that he is a proxy.
For example, Huawei mobile phone is a class, Mate 40 is an instantiated object created, then this Mate 40 can perform all functions in Huawei mobile phone.

Part 1 - Creating objects and calling methods

[Exercise in class] Add a method to the Book1 class to output all the properties in the class.

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

namespace OOPDemo_1
{
    
    
    class Book1
    {
    
    
        public int Id {
    
     get; set; }
        public string Name {
    
     get; set; }
        public double Price {
    
     get; set; }
        public void PrintMsg()
        {
    
    
            Console.WriteLine("图书编号:" + Id);
            Console.WriteLine("图书名称:" + Name);
            Console.WriteLine("图书价格:" + Price);
        }
    }
}

In the Main method of the project's Program.cs file, add the code that calls the PrintMsg() method.

	class Program
	{
    
    
	    static void Main(string[] args)
	    {
    
    
	        Book1 book1 = new Book1();
	        book1.PrintMsg();
	    }
	}

Results of the
insert image description here

Step 2 - Assigning and outputting attributes

Call the corresponding property through the object and assign it:

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Book1 book1 = new Book1();
        //为属性赋值
        book1.Id = 520;
        book1.Name = "围城";
        book1.Price = 131.4;
        book1.PrintMsg();
    }
}

[Classroom Exercise] Add a method for assigning a value to the property in the Book1 class and call it in the Main method.

class Book1
{
    
    
    public int Id {
    
     get; set; }
    public string Name {
    
     get; set; }
    public double Price {
    
     get; set; }
    public void SetBook(int id, string name, double price)
    {
    
    
        Id = id;
        Name = name;
        Price = price;
    }
    public void PrintMsg()
    {
    
    
        Console.WriteLine("图书编号:" + Id);
        Console.WriteLine("图书名称:" + Name);
        Console.WriteLine("图书价格:" + Price);
    }
}

/**********************主函数代码***********************************/
class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Book1 book1 = new Book1();
        book1.SetBook(520, "计围城", 131.4);
        book1.PrintMsg();
    }
}

If you want to get the value of the property, you can use it directly 类的对象.属性名;
if the code to assign the property is as follows:

类的对象 . 属性名 =;

Code to call a method with an object of the class:

类的对象 . 方法名(参数);

Tips: If the members in the class are 修饰符 staticdeclared using , the method can be used directly when accessing the class members 类名.类成员.

insert image description here

[three], knowledge accumulation - commonly used common categories

① Console class - The Console class is mainly used for input and output operations of console applications.

I think it is important at this stage, and there are four commonly used methods:
insert image description here

Supplementary formatted output
In addition, when outputting content to the console, the output content can also be formatted. The placeholder method is used for formatting. The syntax is as follows:
Console.Write(format string, output item 1, output item 2);
where the form of {index number} is used in the format string, and the index number starts from 0. Output item 1 populates the contents of position {0}, and so on.
insert image description here

At this stage, I think there are three attributes that are worth mastering:

insert image description here
As for other more detailed explanations and summaries, you can refer to [ Microsoft C# Official Documentation - Console Class ]

② Math class - Math class is mainly used for some math-related calculations, and provides many static methods for easy access

There are quite a few common methods of the Math class. Note that Max and Min are super common.
insert image description here
Tips: When using it, you must pay attention to the return value type. Before using it, you can refer to the official documentation
[ Math class official documentation ]

③ Random class - Random class is a class that generates pseudo-random numbers

它的构造函数有两种:
New Random()
New Random(Int32)

The former uses the system time at the trigger moment as the seed to generate a random number;
the latter can set the trigger seed by itself, generally using UnCheck((Int)DateTime.Now.Ticks) as the parameter seed.

Common methods in Random: If
insert image description here
you want to learn in depth, you can read an official document [ Random class official document ]

test code

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Random rd = new Random();
        Console.WriteLine("产生一个10以内的数:{0}", rd.Next(0, 10));
        Console.WriteLine("产生一个0到1之间的浮点数:{0}", rd.NextDouble());
        byte[] b = new byte[5];
        rd.NextBytes(b);
        Console.WriteLine("产生的byte类型的值为:");
        foreach(byte i in b)
        {
    
    
            Console.Write(i + " ");
        }
        Console.WriteLine();
    }
}

④ DateTime class - ateTime class is used to represent time

I think this is quite common, and the range represented is from 0:00 on January 1, 0001 to 24:00 on December 31, 9999.

An important static method:

The static property Now is provided in the DateTime class to get the current date and time:
as follows:

DateTime.Now

insert image description here
[ Official document of DateTime structure ]

⑤ Nested class

core knowledge

If you call a member of a nested class in another class, you need 外部类.嵌套类to create an object of the nested class in a way to call its members through the object of the nested class.
If you call a static member in a nested class, you can call it directly 外部类 . 嵌套类 . 静态成员.

Nested class definition:
In addition to writing fields, properties, and methods in a class, you can also define classes directly. When a class is defined inside another class, a class defined inside a class is called a nested class.
Nested classes in C# are equivalent to members of the class, and access modifiers and modifiers for class members can be used. However, when accessing members of a nested class, the name of the enclosing class must be added.

test code

class OuterClass
{
    
    
	//在OuterClaSS 类中 嵌套 InnerClass
    public class InnerClass
    {
    
    
        public string CardId {
    
     get; set; }
        public string Password {
    
     get; set; }
        public void PrintMsg()
        {
    
    
            Console.WriteLine("卡号为:" + CardId);
            Console.WriteLine("密码为:" + Password);
        }
    }
}

/***************************主函数代码****************************************/
class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        OuterClass.InnerClass outInner = new OuterClass.InnerClass();
        outInner.CardId = "1314520";
        outInner.Password = "123456";
        outInner.PrintMsg();
        
        Console.ReadKey();
    }
}

One of the three major characteristics of object-oriented - encapsulation

C# encapsulation sets the user's access rights according to specific needs, and implements it through access modifiers.

one 访问修饰符defines 类成员one 范围和可见性.

public All objects are accessible
private The object itself is accessible inside the object
protected Only objects of this class and their subclasses can access
internal Objects of the same assembly can access

It is enough to know that you need to use these four access modifiers to implement encapsulation, and the specific in-depth development should be combined with the project.
insert image description here

Summarize

For this article, it is important to grasp the following four-board knowledge content:

① Distinguish clearly the access modifiers and modifiers used for classes and the access modifiers and modifiers used for members of the class
② Remember the members in the class, how to construct objects, how to call attributes and methods, and how to modify attribute values
​​③ Accumulation Common classes
④ Know that object-oriented has three major characteristics, and how the encapsulation is implemented.

If you find it useful, welcome to collect articles, subscribe to columns and communicate at any time.
insert image description here

Guess you like

Origin blog.csdn.net/weixin_52621323/article/details/125711810