search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of the construction method and sample code of C# class

This article mainly introduces the construction method of the c# class. It has a certain reference value. Let’s take a look at it with the editor.

1. Construction method

The construction method of a class is the member method# of the class A type of ##, its function is to initialize members in the class. The construction methods of the class are divided into:

1.staticConstruction method

## 2. Instance construction method

1. Static construction method

The static construction method of a class is a type of member method of the class, and its function is Initialize static members in the class. Please see the code example below:

using System;
namespace LycheeTest {
 class Test {
 //定义一个静态成员变量
 private static int a;
 //定义静态构造函数
 static Test() {
  //初始化静态成员变量
  a = 11;
 }
 public void Show() {
  Console.WriteLine("静态字段 a 的值是:{0}", a);
 }
 }
 class Program {
 static void Main(string[] args) {
  Test t = new Test();
  t.Show();
  Console.ReadKey();
 }
 }
}

First of all, the above code defines two classes. Line 3 defines the class Test. When defining a class, there are two access permission modifiers for the class, one is public and the other is internal. When no access modifier is written, the access permission of the class is internal by default. The meaning of this access permission is that this class can only be accessed by this assembly and cannot be accessed by classes outside this assembly. If this class belongs to the

Class Library

, then it must be public, otherwise the assembly that calls it cannot access it. Line 5 of code defines a static field member, and line 7 of code is the static constructor. As you can see, the characteristic of the static construction method is that the static keyword indicates that the method is static, and the method name must be exactly the same as the class name. Pay attention to the case here. Static construction methods cannot contain parameters, and static construction methods cannot have return values. You can initialize static members in the body of the static constructor method. Line 11 of code defines an instance method that outputs the value of a static field. This class is called in the Main (note: main in Java) method in the class Program on line 16, an instance of this class is created on line 18, and the instance method of the class is called on line 19. As you can see from the above code, the static constructor of the class is not explicitly called.

Please see the execution result of the above code below:

The value of static field a is: 11

As you can see, the static construction method is indeed was executed. Then the above example is one of the execution conditions of the static construction method. When an instance of the class is created, the static construction method of the class will be automatically called.

The calling order of the static constructor is after the initializer of the static field.

That is, the first step is to set the default value of the static field, the second step is to execute the initial value setting item of the static field, and the third step is to call the static constructor method of the class.

Let’s modify the previous code example. The code is as follows:

using System;
namespace LycheeTest{
 class Test {
 private static int a;
 static Test() {
  a++;
 }
 public void Show() {
  Console.WriteLine("静态字段 a 的值是:{0}", a);
  14
 }
 }
 class Program {
 static void Main(string[] args) {
  Test t = new Test();
  t.Show();
  Test t1 = new Test();
  t.Show();
  Console.ReadKey();
 }
 }
}

This code modifies the static construction method and increments the static field a in the method body. Then on line 17 of the code, another instance of the class is created, and the class's instance method is called again.

Look at the execution results below:

静态字段 a 的值是:1 
静态字段 a 的值是:1

You can see that the value of the static field has not increased. This is the characteristic of static constructor execution, it is only executed once. When the assembly is run, an application domain will be created. In an application domain, the static construction method of the class is executed only once.

The code example is modified as follows:

using System;
namespace LycheeTest {
 class Test {
 public static int a;
 static Test() {
  Console.WriteLine("类的静态构造方法开始执行");
  a++;
 }
 public void Show() {
  Console.WriteLine("静态字段 a 的值是:{0}", a);
 }
 }
 class Program {
 static void Main(string[] args) {
  Console.WriteLine("静态字段 a 的值是:{0}", Test.a);
  Console.WriteLine("静态字段 a 的值是:{0}", Test.a);
  Console.ReadKey();
 }
 }
}

This code prints out a line of tags in the static construction method of the class, and the access rights of the static fields of the class are also modified to public. This allows it to be called outside the class. The value of the static field is printed out twice in the Main method. Note that when calling the static field of the class outside the class, you need to use the class name for

reference

. The following is the execution result of the code:

类的静态构造方法开始执行
静态字段 a 的值是:1
静态字段 a 的值是:1

This code does not create an instance of the class. Before referencing the static members of the class, the static constructor of the class will be called. The static members of the called class include static fields and static methods. This is the second condition for calling the static constructor method of the class.

The code example will be modified as follows:

using System;
namespace LycheeTest {
 class Program {
 private static int a;
 static Program() {
  Console.WriteLine("类的静态构造方法被调用");
  a = 11;
 }
 static void Main(string[] args) {
  Console.WriteLine("Main 方法被调用");
  Console.WriteLine("静态字段 a 的值是:{0}", a);
  Console.ReadKey();
 }
 }
}

This code defines static fields and static constructors in the class containing the Main method. Because the Main method is also a static method, the static constructor of the class is called and it is the entry point method of the class, so who calls it first between it and the static constructor of the class? Let’s first look at the execution results of the code:

类的静态构造方法被调用
Main 方法被调用
静态字段 a 的值是:11

You can see from the execution results of the code that because the entry point method of the class is still a static method, before any static members are called, the static constructor method is called first. Therefore, it can be concluded that the static constructor of the class is called before the Main method of the class.

So can the static construction method of a class be explicitly called? Look at the code example below:

using System;
namespace LycheeTest {
 class Program {
 private static int a;
 static Program() {
  Console.WriteLine("类的静态构造方法被调用");
  a = 11;
 }
 static void Main(string[] args) {
  Program();
  Console.ReadKey();
 }
 }
}

在这段代码中的第 10 行显式调用了类的静态构造方法,这时编译器会报错。

2.实例构造函数

类的实例构造方法是类的成员方法的一种,它的作用是对类的实例成员进行初始化操作。实例构造方法可以实现重载,在创建类的实例时,可以显式的指定不同的参数来调用重载的不同的实例构造方法。下面请看代码实例:

using System;
namespace LycheeTest {
 class Program {
 private static int a;
 private int b = 12;
 private string c = "Hello World";
 static Program() {
  Console.WriteLine("类的静态构造方法被调用");
  a = 11;
 }
 public Program(int a, string s) {
  Console.WriteLine("带二个参数的构造方法被调用");
  this.b = a;
  this.c = s;
 }
 public Program(int a) : this(a, "通过 this 关键字调用构造方法") {
  Console.WriteLine("带一个参数的构造方法被调用");
 }
 public void Show() {
  Console.WriteLine("静态字段 a 的值是:{0}", a);
  Console.WriteLine("实例字段 b 的值是:{0}", b);
  Console.WriteLine("实例字段 c 的值是:{0}", c);
 }
 static void Main(string[] args) {
  Program p1 = new Program(33, "这是创建的实例 P1");
  Program p2 = new Program(34);
  p1.Show();
  p2.Show();
  Console.ReadKey();
 }
 }

这段代码的第 4 行、第 5 行和第 6 行分别定义了三个字段成员,第 4 行是静态字段,第 5 行和第 6 行代码都有初始值设定项。代码的第 8 行就是一个实例构造方法的定义,实例构造方法也是以类名作为方法名,它没有返回值, 在方法名前面是访问权限修饰符,可以使用的访问权限修饰符包括 public、private 和 protected。其中的 protected 意味着构造方法只能在此类内部访问。实例构造方法可以带参数。 第 12 行代码的实例构造方法使用两个传入的参数对实例字段进行了赋值。第 17 行代码定义了带一个参数的实例构造方法,它和前一个实例构造方法形成了重载。实例构造方法可以通过 this 关键字调用其他的实例构造方法,方法就是在参数列表的后面使用冒号然后接 this 关键字, 然后再跟参数列表,这个参数列表要匹配另一个重载的实例构造方法。第 17 行的构造方法只有一个参数, 它将这个参数通过 this 关键字传递给了另一个构造方法,在用 this 调用另一个构造方法的时候,为其同时传入了一个字符串参数。第 24 行的实例方法打印类的字段成员的值。在 Main 方法中,第 26 行代码和第 27 行代码分别定义了两个实例,它们使用 new 关键字调用了不同的实例构造方法。第 28 行和第 29 行分别调用实例方法打印类的静态字段和实例的两个字段成员的值。

下面先来看代码的执行结果:

类的静态构造方法被调用 带二个参数的构造方法被调用 带二个参数的构造方法被调用 带一个参数的构造方法被调用 
静态字段 a 的值是:11 
实例字段 b 的值是:33
实例字段 c 的值是:这是创建的实例 P1 静态字段 a 的值是:11
实例字段 b 的值是:34
实例字段 c 的值是:通过 this 关键字调用构造方法

现在用执行结果来介绍实例构造方法的执行过程,当第 26 行代码创建类的实例时,类的静态字段首先被设置成默认值,因为没有字段的初始值设定项,所以接着就执行类的静态构造方法。这时静态字段 a 被 设置成 11。因为第 26 行代码使用 new 调用了带有两个参数的实例构造方法,所以首先实例字段 b 被设置为 0,实例字段 c 被设置为 null。然后执行字段的初始值设定项,b 被赋值为 12,c 被赋值为“Hello World”。接 下来执行实例构造方法体中的第一个语句,“带二个参数的构造方法被调用”这个字符串被打印。接下来 实例 p1 的字段 b 被设置为传入的参数 33,注意构造方法的形参 a 在这里覆盖了类的静态字段 a。也就是说, 这时起作用的是实例构造方法的局部变量 a。然后实例字段 c 被设置为字符串"这是创建的实例 P1"。第 27 行代码使用 new 关键字调用了带一个参数的实例构造方法,在调用时,首先属于 p2 的实例字段 b 被设置为 0,实例字段 c 被设置为 null。然后执行字段的初始值设定项,b 被赋值为 12,c 被赋值为“Hello World”。接下来执行的是 this 引用的带两个参数的实例构造方法,"带二个参数的构造方法被调用"这个 字符串被打印。然后 b 被设置为 34,c 被设置为"通过 this 关键字调用构造方法"。最后,代码控制又返回 来执行带一个参数的实例构造方法体中的打印语句,"带一个参数的构造方法被调用"这个字符串被打印。 至此,实例构造方法的执行完毕。接下来的代码打印静态字段的值,可以看到两个实例打印出来的静态字段值是一样的,但是它们的实 例字段的值各不相同。

可选参数和命名参数也可以用于实例构造方法,下面看代码实例:

using System;
namespace LycheeTest {
 class Program {
 private int b;
 private string c;
 public Program(int a = 12, string s = "") {
  this.b = a;
  this.c = s;
 }
 public void Show() {
  Console.WriteLine("实例字段 b 的值是:{0}", b);
  Console.WriteLine("实例字段 c 的值是:{0}", c);
 }
 static void Main(string[] args) {
  Program p1 = new Program(); //构造方法的两个参数都采用默认值
  Program p2 = new Program(34); //构造方法的 string 类型参数采用默认值
  Program p3 = new Program(23, "Hello World"); //构造方法的两个参数采用传入参数
  Program p4 = new Program(s: "今天的天气真好"); //采用命名参数,另一个参数 a 采用默认值
  p1.Show();
  p2.Show();
  p3.Show();
  p4.Show();
  Console.ReadKey();
 }
 }
}

代码的第 6 行定义了一个带有可选参数和命名参数的构造方法,然后第 15 创建了一个类的实例,在构造方法中没有传入任何参数,这时,构造方法的两个参数都采用默认值。第 16 行代码为构造方法传入了一个 int 类型的参数,这时,另一个 string 类型的参数采用默认值。 第 17 行代码传入了两个参数,构造方法的两个参数都使用了这两个传入的参数。第 18 行代码使用了命名参数指定传入的参数是 string 类型的参数,并将它传递给形参 s。这时另一 个 int 类型的参数采用默认值。第 19 行到第 23 行代码打印类的实例字段的值。这段代码的执行结果如下:

实例字段 b 的值是:12 
实例字段 c 的值是: 
实例字段 b 的值是:34 
实例字段 c 的值是: 
实例字段 b 的值是:23
实例字段 c 的值是:Hello World 实例字段 b 的值是:12
实例字段 c 的值是:今天的天气真好

The above is the detailed content of Detailed explanation of the construction method and sample code of C# class. For more information, please follow other related articles on the PHP Chinese website!

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# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

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.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment