C #: a question about static and non-static,

Source: Internet
Author: User

C #: a question about static and non-static,

With regard to the differences between static methods, variables, non-static methods, and variables, the great gods in the garden have long made many detailed summaries, I personally think the differences between static methods, variables, and non-static methods and variables can be summarized as follows:

Static is a class

Non-static objects

That is to say, you can directly use ClassName when calling static methods and variables. staticMethod (); To call non-static methods and variables, you can only create an instance of the class ClassName instance = new CalssName ();, and then call the instance. method ();

However, many people say that static methods can only be static methods and variables in the category class. They have a lot of questions:

        static void Main(string[] args)        {            Test test = new Test();            test.PrintInNotStatic();        }        class Test        {            public static void PrintInStatic()            {                Console.WriteLine("this is in the static method");            }            public void PrintInNotStatic()            {                Console.WriteLine("this is in the not static method");            }        }            

Didn't I call a non-static method here? Why?
After reading materials and thinking, I found myself jumping into a trap and did not notice it.Static methods can only be static methods and variables in the response class.In this sentenceClass.

In the above Code, an object is created and the method is called through the object instead of directly calling the method using the class. As long as you understand the differences between classes and objects, you can easily understand the meaning of this sentence.

Record your questions and hope you can help those who have questions.

This article is a beginner's post. If any errors are found, please kindly advise.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.