Ozz*_*zah 34 c# static-methods static-members
我做了一个小实验:
public abstract class MyClass
{
private static int myInt = 0;
public static int Foo()
{
return myInt;
}
public static int Foo(int n)
{
myInt = n;
return bar();
}
private static int bar()
{
return myInt;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我跑了:
MessageBox.Show(MyClass.Foo().ToString());
MessageBox.Show(MyClass.Foo(3).ToString());
MessageBox.Show(MyClass.Foo().ToString());
MessageBox.Show(MyClass.Foo(10).ToString());
MessageBox.Show(MyClass.Foo().ToString());
Run Code Online (Sandbox Code Playgroud)
我预期的结果是0,3,0,10,0.
令我惊讶的是,我得到了0,3,3,10,10.
这些变化持续多久了?程序执行的持续时间?调用静态方法的函数的持续时间?
Ed *_* S. 27
我预期的结果是0,3,0,10,0.
令我惊讶的是,我得到了0,3,3,10,10.
我不确定为什么你会期望静态变量在从Foo(int)方法中更改后恢复到其原始值.静态变量将在整个过程的生命周期中保持其值,并且每个类只存在一个,而不是实例.