理解构造函数

jas*_*son 3 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.Minute, time.Second) { }

    public void SetTime(int h, int m, int s)
    {
        Hour = h;
        Minute = m;
        Second = s;
    }
Run Code Online (Sandbox Code Playgroud)

除了这部分,我理解了一切:

 public Time2(Time2 time)
            : this(time.hour, time.Minute, time.Second) { }
Run Code Online (Sandbox Code Playgroud)

你能告诉我这个构造函数是如何工作的吗?"this"关键字的风格和工作对我来说看起来很陌生.谢谢.

Cal*_*leb 5

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");
}
Run Code Online (Sandbox Code Playgroud)