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

标签 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;
    }
}


为什么当我将其插入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/

相关文章:

c# - .Net 项目构建问题

c++ - 静态实例的未定义​​引用

c# - 使父类(super class)具有一个静态变量,该变量对于 c# 中的每个子类都不同

c# - 我的漫游数据不在设备之间同步

c# - 在不知道需要显示的图像数量的情况下,如何在 Windows 窗体应用程序中显示图像?

c# - 通用处理程序的集合——这可能吗?

c# - MVVX无法从MvxDefaultViewModelLocator初始化ViewModel

ios - 对类对象使用 objc_setAssociatedObject 是否正确?

javascript - 刷新网页后保留变量的值

python - Python中的高效内存