C#在实例化时递增静态变量

igg*_*012 1 c# static-variables

我有一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么当我将其插入主体时如此:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

savings 1001
savings 1002
Run Code Online (Sandbox Code Playgroud)

但相反,我得到:

savings 1002
savings 1002
Run Code Online (Sandbox Code Playgroud)

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

Bra*_*ore 7

因为静态变量在类的所有实例之间共享.你想要的是一个静态变量来保持全局计数和一个非静态变量来保存实例化时的当前计数.将上面的代码更改为:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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