C# Learning Journey

Start a C# journey

This article will introduce in detail how to write a C# program, the basic structure of the C# program, and also introduce the common writing specifications of the C# program.

1.1 Write your first C# program

(1) Find Visual Studio 2019 in the "Start" menu interface of the windows operating system, and click to open it.
(2) Click "Creative Project" in the Getting Started window of Visual Studio 2019, open the "Create New Project" dialog box, and select "Console Application (.NET Framework)".
(3) Click the "Next" button to open the "Configure New Project" dialog box. The project name in the dialog box is named "Hello_World", select the save path and the framework to be used, and then click the "Create" button to create A console application.
insert image description here
insert image description here
Note:
When setting the project framework, it is recommended to choose a framework with a lower version, such as .NET Framework 4.0, which develops programs with higher compatibility.
Create a console application, use the WriteLine() method to output the "Hello World!" string, the code is as follows.

static void Main(string[] args){
    
    
Console.WriteLine("Hello World!");
Console.ReadLine();
}

Program running result:
insert image description here

1.2 Initial C# program structure

C# program structure can be roughly divided into namespaces, classes, Main() method, identifiers, keywords, statements, and comments. The following is a detailed explanation.

1.2.1 Namespace

It can be said that C# programs are organized using namespaces. Namespaces can act on a program's "internal" organizational system, or on an "external" exposed organizational system. If you want to call a class or method in a namespace, you first need to use the using directive to introduce the namespace. In C#, each namespace is like a warehouse that stores different types. The using command is like a key. The name of the namespace is like the name of the warehouse. You can use the key to open the warehouse with the specified name, and you can get the required data from the warehouse. items.
The basic form of the using directive is:
using namespace name;
create a console application, create a namespace JL.Data, in which there is a class Model, use the using directive to import the namespace JL.Data, and then in the namespace JL. Instantiate the class Model in the namespace JL.Data in the View, and finally call the GetData() method in this class, the code is as follows

using System;
using JL.Data;  //使用uisng 指令引入命名空间JL.Data
namespace JL.View
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Model model = new Model();  //实例化JL.Data中的类Model
            model.GetData();            //调用类Model中的GetData()方法
        }
    }
}
namespace JL.Data                      //建立命名空间JL.Data
{
    
    
    class Model                       //实例化命名空间JL.Data中的类Model
    {
    
    
        public void GetData()
        {
    
    
            Console.WriteLine("欢迎光临");//输出字符串
            Console.ReadLine();
        }
    }
}

The result of the operation is "Welcome".

1.2.2 Classes

A class is a data type that encapsulates data members, function members, and other classes. A class is a template for creating objects. All statements in C# must be inside a class. Classes are the core and basic building blocks of the C# language. Before using any new class, it must be declared. Once a class is declared, it can be used as a new type. In C#, the class keyword is used to declare a class. The syntax is as follows:

[类修饰符] class [类名] [基类或接口]{
    
    
[类体]
}

In C#, a class name is an identifier and must conform to the naming rules for identifiers. The class name should be able to reflect the meaning and purpose of the class. The class name generally adopts a noun with the first letter capitalized, and can also use a combination of multiple words.

1.2.3 Main() method

The Main() method is the entry point of the program. A C# program must contain a Main() method, in which objects can be created and other methods called. There can only be one Main() method in a program, and all Main( ) methods must be static. The Main() method can be modified with three modifiers, namely public, static and void.
public: Indicates that the Main() method is shared, and the entire method can also be called outside the class.
stataic: Indicates that the Main() method is a static method. Static methods cannot use instantiated objects of the class and must be called directly using the class name.
void: This modifier indicates that the Main() method has no return value.

1.2.4 Identifiers and keywords

1. Identifier

Can be understood as a name, a valid character sequence used to identify, variable name, method name, array name, file name.
The C# language stipulates that identifiers are composed of letters, underscores (_) and numbers, and the first character cannot be a number. Identifiers cannot be keywords in C#.
The following are legal identifiers:
_name
ID
In the C# language, letters in identifiers are strictly case-sensitive, such as good and Good are two different identifiers.

2. Keywords

Here are some commonly used keywords I collected:

int public this finally boolean abstract
continue float long short throw return
break for foreach static new interface
if goto default byte do case void
try switch else catch private
double protected while char class using

1.2.5 C# statements

A statement is the basic unit of constructing all C# programs. Statements can declare local variables or constants, call methods, create objects, or assign values ​​to variables, properties, or fields. Statements are usually terminated with a semicolon.
For example:

Console.WriteLine("欢迎光临");

This statement is to call the WriteLine() method in the Console class to output the specified content "Welcome".

1.2.6 Notes

The compiler does not execute the commented code or text when compiling the program. Its main function is to explain a certain piece of code to facilitate the understanding and maintenance of the code. Comments can be divided into line comments and quick comments. Line comments start with "//"
For example:

static void Main(string[] args) //程序的Main()方法
        {
    
    
            Console.WriteLine("欢迎光临");//输出“欢迎光临”
            Console.ReadLine();
        }

If the number of commented lines is small, line comments are generally used. For large comments , start with "/" and end with "/".
For example:

/*程序的Main()方法中可以输出字符串               //块注释开始
       static void Main(string[] args)            //Main()方法
        {
            Console.WriteLine("欢迎光临");       //输出字符串
            Console.ReadLine();
        }*/

1.3 Code writing rules

Code writing rules usually have no effect on the functionality of the application, but they can be helpful in improving the understanding of the source code.
1. Try to use the interface, and then use the class to implement the interface to improve the flexibility of the program.
2. Try not to manually change the code generated by the computer. If it must be changed, it must be changed to the same style as the code generated by the computer.
3. Key statements (including declaring key variables) must be commented.
4. It is recommended that local variables be declared closest to the place where they are used.
5. Do not use the goto series of statements unless it is used to jump out of a deep loop.
6. Avoid writing more than 5 meals and lodging methods. If you want to pass multiple parameters, use a struct.
7. Avoid writing try-catch code blocks with too much code.
8. Avoid placing multiple classes in the same file.
9. When generating and building a long string, be sure to use the StringBuilder type instead of the string type.
10. The switch statement must have a default statement to handle unexpected situations.
11. For the if statement, a pair of "{}" should be used to enclose the statement block.
12. Try not to use this keyword reference.

1.3.2 Naming convention

Naming conventions play a very important role in writing code. Although the program can run without following the naming conventions, using the naming conventions can intuitively understand the meaning of the code.
1. Use Pascal rules to name methods and types. Pascal's naming rules are that the first letter must be capitalized, and the first letter of the following conjunctions must be capitalized.
For example:

class Model                       
    {
    
    
        public void GetData()
        {
    
    
            
        }
    }

2. Use Camel rules to name local variables and method parameters. Camel rules mean that the first letter of the first word in the name is lowercase, and the first letter of the conjunction is uppercase.
For example:

string strUserName;                                  //声明一个字符串变量strUserName
public void addUser(string strUserName);             //创建一个具有两个参数的公共方法

3. Prefix "_" to all member variables
For example: declare a private member variable _connectionString in the public class DataBase,

public class DataBase{
    
                             //创建一个公共类
     private string_connectionString;          //声明一个私有成员变量
}

4. The name of the interface is prefixed with "I".
For example, to create a public interface Iconvertible,

public interface Iconvertible{
    
                   //创建一个接口
    byte ToByte();                          //声明一个byte类型的方法
}

When defining a method with a return value, you must define the type of the method when setting the method, and use return to return the value after the method body is finished.

Guess you like

Origin blog.csdn.net/weixin_63284756/article/details/128266757