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

Pok*_*mon 1 c# oop

为什么我们不能用instance variable一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sal*_*ari 6

试图在方法中放置一个非静态变量static会让编译器想知道我应该更新这个变量的哪个实例?这些 static方法与类实例无关,因此如果不存在实例,则无法在实例上调用实例变量.