C# 理解构造函数

C# 理解构造函数,c#,constructor,C#,Constructor,我有一段代码: public class Time2 { private int hour; private int minute; private int second; public Time2(int h = 0, int m = 0, int s = 0) { SetTime(h, m, s); } public Time2(Time2 time) : this(time.hour, time.M

我有一段代码:

public class Time2
{
    private int hour;
    private int minute;
    private int second;

    public Time2(int h = 0, int m = 0, int s = 0)
    {
        SetTime(h, m, s);
    }

    public Time2(Time2 time)
        : this(time.hour, time.Minute, time.Second) { }

    public void SetTime(int h, int m, int s)
    {
        Hour = h;
        Minute = m;
        Second = s;
    }
除了这一部分,我什么都懂:

 public Time2(Time2 time)
            : this(time.hour, time.Minute, time.Second) { }
你能告诉我这个构造函数是如何工作的吗?“this”关键字的样式和工作对我来说非常陌生。谢谢。

在该构造函数中执行代码之前,调用并调用该特定构造函数


您还可以使用
:base
,这将调用基类中的相关构造函数(如果您的类当然扩展了任何内容)

此构造函数将使用给定
Time2
实例中的数据调用第一个构造函数

代码:
this
在执行其自身函数的代码之前,正在调用类上的另一个构造函数

试试这个:看看控制台中的输出

public Time2(int h = 0, int m = 0, int s = 0)
{
    Console.Log("this constructor is called");
    SetTime(h, m, s);
}

public Time2(Time2 time)
    : this(time.hour, time.Minute, time.Second) 
{
    Console.Log("and then this constructor is called after");
}

然后它会做什么?@jason它使用给定Time2的值,并将小时、分钟和秒设置为该实例的小时、分钟和秒。当一个类声明多个(非静态)构造函数时,我们有一个重载示例。在这种情况下,一个构造函数重载可以使用您提到的语法链接另一个构造函数重载。链接的构造函数体(在您的示例中为
Time2(int,int,int)
)首先运行,然后链接构造函数体(此处为
Time2(Time2)
)运行(在您的示例中,该体为空
{}
)。在使用继承时,此语法还用于调用基类中的构造函数。使用关键字
base
代替
this
。(并且在继承类的构造函数中执行代码之前,将调用基调用中相应的构造函数。
public Time2(int h = 0, int m = 0, int s = 0)
{
    Console.Log("this constructor is called");
    SetTime(h, m, s);
}

public Time2(Time2 time)
    : this(time.hour, time.Minute, time.Second) 
{
    Console.Log("and then this constructor is called after");
}