【问题标题】:Understanding a constructor了解构造函数
【发布时间】:2014-08-04 18:16:33
【问题描述】:

我有这段代码:

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”关键字的风格和工作对我来说非常陌生。谢谢。

【问题讨论】:

  • 当一个类声明多个(非静态)构造函数时,我们有一个重载的例子。在这种情况下,构造函数重载之一可以使用您提到的语法 chain 另一个。链接的构造函数的主体(在您的示例中为Time2(int, int, int))首先运行,然后链接构造函数的主体(此处为Time2(Time2))运行(在您的示例中该主体为空{ })。

标签: c# constructor


【解决方案1】:

这称为constructor chaining,并在执行该构造函数中的代码之前调用该特定构造函数。

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

【讨论】:

    【解决方案2】:

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

    代码:

    Time2 TwoHours = new Time2(2, 0, 0);
    TwoHours.SetTime(0, 120, 0);
    Time2 2Hours = new Time2(TwoHours);
    
    // 2Hours will have 0 Hours, 120 Min and 0 Seconds
    

    【讨论】:

    • 然后它的作用是什么?
    • @jason 它使用给定 Time2 中的值并将小时、分钟和秒设置为该实例的值。
    【解决方案3】:

    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");
    }
    

    【讨论】:

    • 此语法也用于在使用继承时调用基类中的构造函数。使用关键字base 代替this。 (并且在继承类上执行构造函数中的代码之前,会调用基调用中对应的构造函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2020-05-23
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多