什么是“本”在C#构造函数是什么意思? [英] What does 'this' mean in a c# constructor?

查看:109
本文介绍了什么是“本”在C#构造函数是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C#和我通过一本教科书的工作。
教科书显示这段代码:

I am very new to c# and I am working through a textbook. The textbook shows this piece of code:

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...



我无法理解这样的:

I am having trouble understanding this:

public BankAccount() : this(0)
{
}

它的看起来的继承语法,但我想这不是因为这(0)是不是一类。我不认为这会使得逻辑意义,从正在使用相同的类继承。这可能是一个构造函数和语法困惑我。

It looks like the syntax for inheritance, but I guess it isn't because this(0) is not a class. And I don't think it would make logical sense to inherit from the same class that is being used. It is probably a constructor and the syntax is confusing me.

这是什么这(0)是什么意思?为什么要使用这个,有另一种方式来写呢?

What does this(0) mean? Why use this, is there another way to write it?

这会是一样的?:

public BankAccount()
{
  BankAccount(0);
}



我了解以下内容:

I understand the following:

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



这似乎是一个接受差额值的构造,并设置帐户号。

It appears to be a constructor that accepts a balance value, and sets the account number.

我的猜测是,这(0)其实只是执行的BankAccount (0)。如果这是真的,为什么还要写两个构造函数? 的BankAccount(0)似乎很好地工作。

My guess would be that this(0) is really just executing BankAccount(0). If this is true, why bother writing two constructors? BankAccount(0) seems to work fine.

有人能解释什么这个是一个简单的方法(新的C#,Python的未来)?

推荐答案

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

Your guess is correct, this(0) is calling the BankAccount(decmial) constructor.

您可以创建两个原因就是给你一类消费者选择。如果他们有他们的价值可以使用 BackAccount(十进制)的构造函数,如果他们不关心他们可以用几秒钟自救的BankAccount()的构造函数,它将初始化平衡到一个合理的值。此外,如果你曾经想改变默认,你可以在一个地方这样做。

The reason you might create two is to give the consumer of your class a choice. If they have a value they can use the BackAccount(decimal) constructor, if they don't care they can save themselves a few seconds by using the BankAccount() constructor and it will initialize the balance to a reasonable value. In addition, if you ever wanted to change the default you can do so in one place.

这篇关于什么是“本”在C#构造函数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆