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

前端 未结 6 636
执笔经年
执笔经年 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 04:09

    Instance methods rely on state of that particular instance in order to run.

    Let's say you had this class which has the scenario you describe:

    class Person
    {
        static PrintName()
        {
            // Not legal, but let's say it is for now.
            Console.WriteLine(Name);
        }
    
        private Name { get; set; }
    }
    

    Hopefully, the problem is apparent now. Because Name is an instance member, you need an actual instance of the class, since Name can be different across different instances.

    Because of this, the static method, which is not attached to an instance, doesn't know which instance to use. You have to be explicit in specifying which one.

提交回复
热议问题