c# - C# - 滥用静态变量
问题描述
我在 PR 中有一个像下面这样的类(为了目的而重构),现在正在度假的一位前辈说我滥用了静态变量,我应该将变量从一个方法传递到另一个方法。
class Class {
static int dataPool;
// the below methods are called cyclicly for the duration of the application,
// xxxx times, First method is called and then Second is called,
// over and over
public static void First()
{
// at the start, reads dataPool count to do computation
// at the end, set dataPool count based on computation
}
public static void Second()
{
// at the start, read dataPool count to do some computation
// at the end, set dataPool count based on computation
}
}
我想了解为什么使用像上面这样的变量是“不好的”学习。谁能解释一下吗?
解决方案
我想了解为什么使用像上面这样的变量是“不好的”学习。谁能解释一下?
主要原因:
- 这意味着您的代码不再是可重入的。
- 这意味着您的代码不再是线程安全的(甚至是更少的线程安全)并且不能同时运行。
- 这意味着您的代码在意想不到的地方有状态(请参阅:最小惊讶原则)。
- 这意味着您的代码将在多线程系统中表现不佳(即使它是严格的单线程且没有可重入性),因为具有可变静态状态意味着您的编译器无法优化程序对内存的使用,因为它无法保证数据的线程所有权。缓存一致性是昂贵的。
- 这意味着您无法正确地对代码进行单元测试(使用“单元测试”的严格定义,而不是 Visual Studio 的)。
- 这意味着 JIT 编译器无法尽可能地优化您的程序,否则因为推理静态状态的生命周期非常困难。
- 这意味着如果另一个函数或线程决定在您不知情的情况下改变您的静态状态,您的代码可能会被破坏。