【发布时间】:2015-02-27 15:01:01
【问题描述】:
我对 c# 非常陌生,并且正在阅读一本教科书。 教科书上显示了这段代码:
public class BankAccount
{
// Bank accounts start at 1000 and increase sequentially.
public static int _nextAccountNumber = 1000;
// Maintain the account number and balance for each object.
public int _accountNumber;
public decimal _balance;
// Constructors
public BankAccount() : this(0)
{
}
public BankAccount(decimal initialBalance)
{
_accountNumber = ++_nextAccountNumber;
_balance = initialBalance;
}
// more methods...
我无法理解这一点:
public BankAccount() : this(0)
{
}
它看起来像继承的语法,但我猜这不是因为this(0) 不是一个类。而且我认为从正在使用的同一个类继承是不合逻辑的。它可能是一个构造函数,语法让我感到困惑。
this(0) 是什么意思?为什么要用this,有没有别的写法?
也一样吗?:
public BankAccount()
{
BankAccount(0);
}
我了解以下内容:
public BankAccount(decimal initialBalance)
{
_accountNumber = ++_nextAccountNumber;
_balance = initialBalance;
}
它似乎是一个接受余额值并设置帐号的构造函数。
我的猜测是 this(0) 实际上只是在执行 BankAccount(0)。如果这是真的,为什么还要编写两个构造函数呢? BankAccount(0) 似乎工作正常。
谁能用简单的方式解释this是什么(c#新手;来自python)?
【问题讨论】:
-
它调用其他构造函数
-
在 C# 中,您不能从另一个构造函数的 body 调用构造函数。 (
Would this be the same?:示例) -
您需要无参数构造函数的一个原因是序列化stackoverflow.com/questions/267724/…
标签: c# constructor this