Static and instance methods

Topic description  

Static methods and instance methods. (console application)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace static methods and instance methods (the program does not need to be executed)
{
    class Program
    {
        int exampleVar = 0;//Instance member
        static int staticVar = 0;//Static member
        static void staticMethod()//Static method, instance members cannot be called in static methods
        {
            staticVar = 1;
        }
        void exampleMethod()//Instance method, you can call any member, including static and instance classes
        {
            staticVar = 1;//Equivalent to this.staticVar = 1
            exampleVar = 1;
        }
        static void Main(string[] args)
        {
            Program.staticMethod();//Call directly when calling a static method
            Program p = new Program();//It must be instantiated when calling an instance method
            p.exampleMethod();
        }
    }
}

***Static methods can only access static members

    Instance methods can access static and instance members

   The reason why static methods are not allowed to access instance member variables is because instance members belong to an object, and the object does not necessarily exist when a static method is executed. Also, because instance methods can access instance member variables, allowing static methods to call instance methods will indirectly allow static methods to use member variables, which is wrong. For the same reason, static methods cannot use the keyword this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325956615&siteId=291194637