'this' 在 C# 构造函数中意味着什么?

What does 'this' mean in a c# constructor?

我是 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)不是class。而且我认为从正在使用的相同 class 继承在逻辑上没有意义。它可能是一个构造函数,语法让我感到困惑。

this(0)是什么意思?为什么要用this,还有别的写法吗?

这会是一样的吗?:

public BankAccount()
{
  BankAccount(0);
}

我了解以下内容:

public BankAccount(decimal initialBalance)
    {
        _accountNumber = ++_nextAccountNumber;
        _balance = initialBalance;
    }

它似乎是一个接受余额值并设置帐号的构造函数。

我的猜测是 this(0) 实际上只是在执行 BankAccount(0)。如果这是真的,为什么还要写两个构造函数呢? BankAccount(0) 似乎工作正常。

谁能用简单的方式解释一下 this 是什么(c# 新手;来自 python)

在这里的上下文中,它的意思是“当调用构造函数 public BankAccount() 时,执行另一个构造函数,匹配签名。0 匹配 public BankAccount(decimal initialBalance),导致该构造函数也被调用。

关键字 this 也可以应用于其他上下文,但它始终指的是 class 的当前实例。这也意味着它不存在于静态 classes 中,因为它们没有被实例化。

您的猜测是正确的,this(0) 正在调用 BankAccount(decmial) 构造函数。

您创建两个的原因是为了让 class 的消费者有选择的余地。如果他们有一个值,他们可以使用 BackAccount(decimal) 构造函数,如果他们不在乎,他们可以使用 BankAccount() 构造函数为自己节省几秒钟,它将余额初始化为一个合理的值。此外,如果您想更改默认设置,您可以在一处进行。

表示构造函数调用同一个class的另一个构造函数。 调用哪个构造函数取决于int签名。

在这种情况下 this(0) 将调用唯一匹配的构造函数 BankAccount(decimal initialBalance),因为 0 可以作为 decimal.

传递