无法在静态方法中使用实例变量

本文关键字:实例 变量 静态方法 | 更新日期: 2023-09-27 18:12:39

为什么不能在static method中使用instance variable ?我知道静态方法调用没有创建类的实例,但什么限制非静态变量在静态方法中使用?

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方法与类实例无关,因此当实例不存在时,在实例上调用实例变量是不可能的。