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

前端 未结 6 628
执笔经年
执笔经年 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:15

    Static functions can only use static members, and call static functions.

    As mentioned, a static function can operate on a class instance, but not from within a class instance (for lack of a more descriptive word). For example:

    class MyClass
    {
        public int x;
        public static int y;
    
        public static void TestFunc()
        {
            x = 5; // Invalid, because there is no 'this' context here
            y = 5; // Valid, because y is not associated with an object instance
        }
    
        public static void TestFunc2(MyClass instance)
        {
            instance.x = 5; // Valid
            instance.y = 5; // Invalid in C# (valid w/ a warning in VB.NET)
        }
    }

提交回复
热议问题