相关疑难解决方法(0)

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

我有一个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)

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

c# static-variables

1
推荐指数
1
解决办法
9220
查看次数

标签 统计

c# ×1

static-variables ×1