首页 > 解决方案 > 静态字段没有改变?

问题描述

我是 C# 新手,只是一个关于静态字段的问题。假设我们有以下类:

 class SavingsAccount
    {
        public double currBalance;

        // A static point of data.
        public static double currInterestRate = 0.04;

        public SavingsAccount(double balance)
        {
            currBalance = balance;
        }

        // Static members to get/set interest rate.
        public void SetInterestRate(double newRate)
        { 
            currInterestRate = newRate; 
        }

        public static double GetInterestRate()
        { 
            return currInterestRate; 
        }
    }
...
static void Main(string[] args)
        {
            SavingsAccount s1 = new SavingsAccount(50);
            Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate());
            s1.SetInterestRate(0.09);
            SavingsAccount s2 = new SavingsAccount(100);
            Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate());
            Console.ReadLine();
        }

输出是:

Interest Rate is: 0.04
Interest Rate is: 0.09

我了解静态字段适用于类级别,但是当我们创建 s2 时:

SavingsAccount s2 = new SavingsAccount(100);

这不是public static double currInterestRate = 0.04;将 currInterestRate 重置回 0.04 吗?为什么是 0.09?CLR 做了什么使它不被重置?

标签: c#oop

解决方案


那不是 public static double currInterestRate = 0.04;将 currInterestRate 重置回 0.04?

不,静态字段属于类范围。因此,无论您创建多少SavingsAccount对象,都只currInterestRate存在一个。

请注意,当您创建一个新SavingsAccount对象时,实例字段被初始化,然后构造函数被执行,但静态字段保持不变。请不要认为方法之外的整个代码段都被执行了。


推荐阅读