Why can I only access static members from a static function?

前端 未结 6 626
执笔经年
执笔经年 2020-12-10 03:48

I have a static function in a class.

whenever I try to use non static data member, I get following compile error.

An object reference is required for the non

6条回答
  •  离开以前
    2020-12-10 04:20

    A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference.

    In fact, you can access a non-static member in a static context by specifying the object reference explicitly:

    class HelloWorld {
       int i;
       public HelloWorld(int i) { this.i = i; }
       public static void Print(HelloWorld instance) {
          Console.WriteLine(instance.i);
       }
    }
    
    var test = new HelloWorld(1);
    var test2 = new HelloWorld(2);
    HelloWorld.Print(test);
    

    Without explicitly referring to the instance in the Print method, how would it know it should print 1 and not 2?

提交回复
热议问题