public Racer(int id, string firstName, string lastName, string country)
:this(id, firstName, lastName, country, wins: 0)
{ }
为什么会这样
(id, firstName, lastName, country, wins: 0)
使用了什么目的
之间的区别是什么:
public Racer(int id, string firstName, string lastName, string country)
:this(id, firstName, lastName, country, wins: 0) { }
和
public Racer(int id, string firstName, string lastName, string country, int wins)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Country = country;
this.Wins = wins;
}
答案 0 :(得分:1)
正如您所见并发布的那样:
public Racer(int id, string firstName, string lastName, string country)
:this(id, firstName, lastName, country, wins: 0)
{
}
public Racer(int id, string firstName, string lastName, string country, int wins)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Country = country;
this.Wins = wins;
}
这只是意味着你有一个Racer
类,而你上面的内容是constructors
类的两个重载Racer
。请注意,第一个构造函数没有int wins
,但第二个构造函数的最后一个参数确实为int wins
。
this
是指Racer
class
的实例。因此,您可以使用上述两种方法之一(保存默认构造函数)创建Racer
class
的实例,如下所示:
Racer racer1 = new Racer(1, "first", "last", "country"); //taking the first constructor
//or
Racer racer1 = new Racer(1, "first", "last", "country", 5); //taking the second constructor
现在,当您使用第一个constructor
创建class
的实例时(这就是您提出的问题):
public Racer(int id, string firstName, string lastName, string country)
:this(id, firstName, lastName, country, wins: 0)
{
}
这只是意味着
“当您想使用此构造函数创建类实例时 如果不指定
wins
,请使用第二个构造函数来创建它 通过指定wins = 0“。
或者换句话说,第一个constructor
使用第二个constructor
来创建Racer
class
的实例。
也就是说,为了表示内部发生的事情,就好像你改变了一样:
Racer racer1 = new Racer(1, "first", "last", "country"); //you create by the first constructor
进入
//But internally it uses the second constructor with wins=0
Racer racer1 = new Racer(1, "first", "last", "country", 0); //note the zero
同样,它是constructor
,它调用另一个constructor
初始化来创建class
的新实例。 this
只是引用当前构建的class
Racer
的实例。
为什么我们使用它? 为了节省我们的编码!如果我们没有constructor
可以使用其他constructor
来创建class
的实例,请执行以下操作:
public Racer(int id, string firstName, string lastName, string country)
:this(id, firstName, lastName, country, wins: 0)
{
}
然后,当我们想要创建overloaded constructor
时,我们无法使用其他constructor
,我们必须这样做:
public Racer(int id, string firstName, string lastName, string country)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Country = country;
this.Wins = 0; //note the zero, and the above four lines are identical with the other constructor.
}
这似乎是多余的。
答案 1 :(得分:0)
这称为构造函数链接。
C#
允许使用this(...)
关键字从被调用的构造函数中调用另一个构造函数。
让我们举一个例子(你在评论中提供),第一个构造函数不带wins
参数,因此调用了重载的构造函数提供默认值(在这种情况下为0
)。
如果在提供wins
的情况下调用对象创建,则将调用第二个构造函数,该构造函数具有wins参数。
public Racer(int id, string firstName, string lastName, string country)
:this(id, firstName, lastName, country, wins: 0)
{
}
public Racer(int id, string firstName, string lastName, string country, int wins)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Country = country;
this.Wins = wins;
}
使用构造函数的好处是它保证对象在使用对象之前经过适当的初始化,这意味着我们可以在使用对象之前用值预初始化一些类变量。