本文介绍了无法在静态方法中使用实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我们不能在static method
中使用instance variable
?我知道静态方法是在不创建类实例的情况下调用的,但是什么限制了非静态变量在静态方法中的使用呢?
Why we cannot use instance variable
in a static method
?I know that static methods are called without creating instance of classes but what restricts the non static variable to be used in static method?
class MyClass
{
// non-static instance member variable
private int a;
//static member variable
private static int b;
//static method
public static void DoSomething()
{
//this will result in compilation error as "a" has no memory
a = a + 1;
//this works fine since "b" is static
b = b + 1;
}
}
推荐答案
尝试将非静态变量放入static
方法中会使编译器感到疑惑,我应该真正更新该变量的哪个实例? static
方法与类实例无关,因此,当不存在任何实例时,将不可能在实例上调用实例变量.
Trying to put a non-static variable inside a static
method makes the compiler wonder which instance of this variable should I really be updating? The static
methods are not related to a class instance, so it will be impossible to call an instance variable on an instance when no instance exists.
这篇关于无法在静态方法中使用实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!