我有一个bankAccount对象,我想使用构造函数来增加。目的是使类实例化的每个新对象都增加它。

注意:我已经重写ToString()以显示accountType和accountNumber;

这是我的代码:

public class SavingsAccount
{
    private static int accountNumber = 1000;
    private bool active;
    private decimal balance;

    public SavingsAccount(bool active, decimal balance, string accountType)
    {
        accountNumber++;
        this.active = active;
        this.balance = balance;
        this.accountType = accountType;
    }
}


为什么当我将其插入main时像这样:

class Program
{
    static void Main(string[] args)
    {
        SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings");
        SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings");
        Console.WriteLine(potato.ToString());
        Console.WriteLine(magician.ToString());
    }
}


我得到的输出不会单独增加它,即

savings 1001
savings 1002


但是我得到了:

savings 1002
savings 1002


我如何使其成为前者而不是后者?

最佳答案

因为在类的所有实例之间共享静态变量。您需要一个静态变量来保留全局计数,而一个非静态变量来保存实例化时的当前计数。将上面的代码更改为:

public class SavingsAccount
{
    private static int accountNumber = 1000;
    private bool active;
    private decimal balance;
    private int myAccountNumber;

    public SavingsAccount(bool active, decimal balance, string accountType)
    {
        myAccountNumber = ++accountNumber;
        this.active = active;
        this.balance = balance;
        this.accountType = accountType;
    }
}

class Program
{
    static void Main(string[] args)
    {
        SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings");
        SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings");
        Console.WriteLine(potato.ToString());
        Console.WriteLine(magician.ToString());
    }
}


然后在ToString()重载中,应打印myAccountNumber而不是静态变量。

关于c# - C#在实例化时递增静态变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8132413/

10-13 01:55