从 C# 中的另一个构造函数调用构造函数
本教程将讨论在 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)
构造函数之前执行。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。