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

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

 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而不是静态变量。

因为它是一个静态变量。 它由类的所有实例共享。 您需要将递增的值保存到实例变量。

 public class SavingsAccount { private static int accountNumberCounter = 1000; private int accountNumber; private bool active; private decimal balance; public BankAccount(bool active, decimal balance, string accountType) { accountNumberCounter++; this.accountNumber = accountNumberCounter; this.active = active; this.balance = balance; this.accountType = accountType; } public string ToString() { return String.Format("{0} {1}", accountType, accountNumber); } } 

您已将变量account声明为static,这意味着它在类级别而非实例级别实例化。 因此,当您执行增量时,对于一个变量,它会发生两次。

实现所需目标的可能方法是在两者之间插入print命令。

试试这个:

 public class SavingsAccount { private static int accountNumberMarker = 1000; private int accountNumber; private bool active; private decimal balance; public SavingsAccount(bool active, decimal balance, string accountType) { accountNumber = ++accountNumberMarker; this.active = active; this.balance = balance; this.accountType = accountType; } } 

你可以试试

  SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings"); Console.WriteLine(potato.ToString()); SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings"); Console.WriteLine(magician.ToString()); 

那么,你可以得到你想要的。

静态变量在整个运行时只有一个副本。 无论创建类的实例多少次,变量都指向相同的内存位置。

因为静态与类中的所有成员共享?

您想要一个静态变量,就像您现在拥有的可以递增的全局数字一样,但您还需要一个特定于该帐户的私有变量。 因此,您应该添加:

 private int thisAccountNumber; 

…到类定义,并修改构造函数中的现有行以读取:

 thisAccountNumber = accountNumber++; 

然后使用thisAccountNumber