c# - 静态字段没有改变?
问题描述
我是 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 做了什么使它不被重置?
解决方案
那不是 public static double currInterestRate = 0.04;将 currInterestRate 重置回 0.04?
不,静态字段属于类范围。因此,无论您创建多少SavingsAccount
对象,都只currInterestRate
存在一个。
请注意,当您创建一个新SavingsAccount
对象时,实例字段被初始化,然后构造函数被执行,但静态字段保持不变。请不要认为方法之外的整个代码段都被执行了。
推荐阅读
- node.js - 安装nodemon的问题
- r - 在 R 中使用环境和 ggplot2 进行故障排除
- c - 访问大型堆数组时出现分段错误(核心转储)
- algorithm - 使用主定理方法求解递归 T(n) = T(n / 2) - T(n / 6) + O(lg n)?
- javascript - 如何在javascript中获得曲线的边界框
- ffmpeg - 使用 ffmpeg 分析来自 Wirecast 的单播流
- c++ - 如何在集群上存储 TB 大小的 C++ 数组
- javascript - 删除数组中的空双引号元素,同时保留其他元素
- javascript - JS:运行 Array.every() 来检查 API 查询参数。返回假
- java - 我试图从带有java字符串输入的txt文件中提取特定的单词