从 C# 中的另一个构造函数调用构造函数
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp Class
本教程将讨论在 C# 中从同一个类的另一个构造函数调用一个构造函数的方法。
在 C# 中使用 this 关键字从同一个类的另一个构造函数调用一个构造函数
如果我们的类有多个构造函数,而我们又想从另一个构造函数调用一个构造函数,则可以在 C# 中使用 this 关键字。this 关键字是对 C# 中当前类实例的引用。以下代码示例向我们展示了如何使用 C# 中的 this 关键字从同一个类的另一个构造函数调用一个类的一个构造函数。
using System;
namespace call_another_constructor {
class sample {
public sample() {
Console.WriteLine("Constructor 1");
}
public sample(int x) : this() {
Console.WriteLine("Constructor 2, value: {0}", x);
}
public sample(int x, int y) : this(x) {
Console.WriteLine("Constructor 3, value1: {0} value2: {1}", x, y);
}
}
class Program {
static void Main(string[] args) {
sample s1 = new sample(12, 13);
}
}
}
输出:
Constructor 1
Constructor 2, value: 12
Constructor 3, value1: 12 value2: 13
我们使用 3 个不同的构造函数创建了 sample 类。构造函数 sample(int x, int y) 调用构造函数 sample(int x),并将 x 作为参数传递给 x。然后,构造函数 sample(int x) 用 this() 调用构造函数 sample()。sample() 构造函数在 sample(int x) 构造函数之前执行,而 sample(int x) 构造函数在 sample(int x, int y) 构造函数之前执行。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn