The static usage of C # is detailed

Source: Internet
Author: User
Tags instance method static class

Some things you use every day, but not necessarily on behalf of you really understand it, as I have known before the static. one, static class

The important difference between a static class and a Non-static class is that a static class cannot be instantiated, that is, you cannot use the New keyword to create a variable of a static class type. Using the static keyword when declaring a class has two meanings: first, it prevents the programmer from writing code to instantiate the static class, and secondly, it prevents any instance fields or methods from being declared inside the class.

  1, the main characteristics of static classes:

[1] contains only static members.

[2] cannot be instantiated.

[3] The nature of the static class is an abstract sealed class, so it cannot be inherited or instantiated.

[4] cannot contain an instance constructor.

[5] If all members of a class need to be shared, then this class can be defined as a static class.

  2. Difference between static class and private constructor:

[1] Private constructor methods can still be instantiated from the inside of a class, while static classes prohibit instantiating classes from anywhere, including from within the class itself.

[2] In a class that uses a private constructor, an instance member is allowed, and the compiler does not allow any instance members of the static class.

[3] The advantage of using static classes is that the compiler is able to perform checks to ensure that instance members are not accidentally added, and the compiler guarantees that no instances of this class will be created.

[4] The C # compiler will automatically mark it as sealed. This keyword specifies the class as not extensible; in other words, you cannot derive other classes from it. second, static members

1, through the static keyword modification, is a class, the instance member belongs to the object, when this class is first loaded, all the static members under this class will be loaded.

2, static members are only created once, so there is only one static member, the instance member has how many objects, how many.

3, class loading, all static members will be created in the "Static storage area", once created until the program exits, will be recycled.

4, when the members need to be shared, methods need to be repeatedly called, you can define these members as static members.

5. In a static method, an instance member cannot be called directly because the object may not exist when the static method is invoked.

6. The This/base keyword cannot be used in static methods because it is possible that the object does not exist yet.

7, you can create objects of this class, make the members of the object operate in the static method.

8. In instance methods, static members can be invoked because static members must exist at this time.

9. A non-static class can contain static methods, fields, properties, or events;

10. No matter how many instances are created for a class, its static members have only one copy;

11. Static methods and properties cannot access non-static fields and events in their containing types, and cannot access instance members of any object;

12. Static methods can only be overloaded, not overridden, because static methods do not belong to instance members of the class;

13, although a field cannot be declared static const, the behavior of the Const field is inherently static. Such fields belong to the class and do not belong to instances of the class. third, static method

1, static method is not belong to a specific object of the method;

2, static methods can access static members;

3, static method can not directly access the instance members, can be in the case of the instance function call, instance members as parameters to the static method;

4, the static method also cannot call the instance method directly, can call indirectly, first creates an instance of a class, then calls the static method through this particular object. four, static constructors

1, static class can have static constructor function, static constructor is not inheritable;
2, static constructors can be used for static classes, but also for non-static classes;
3, static constructors have no access modifiers, no parameters, only a static flag;
4. A static constructor cannot be called directly, and the static constructor is executed automatically and only once before the class instance is created or any static members are referenced.

For example:

Class program
 {public
         static int i =0;
         Public program ()
         {
             i = 1;
             Console.Write ("instance construction method is called");
         }
         Static program ()
         {
             i = 2;
             Console.Write ("Static constructor executed");
         }
         static void Main (string[] args)
         {
             console.write (PROGRAM.I);//The result is 2, first, the class is loaded, all the static members are created in the static storage area, I=0, Then the members of the class are called, and the static constructor is invoked, i=2 program
             p = new program ();
             Console.Write (PROGRAM.I);//The result is 1, after the strength, the instance constructor is invoked, I=1, because the static constructor executes only once, so it is not executed again.
         }
 }
v. Storage of static Members

Use the static modifier to declare static members that belong to the type itself, rather than to a particular object, can be used for classes, fields, methods, properties, operators, events, and constructors, but not for indexers, destructors, or types other than classes.

  Static global Variables

Definition: Before the global variable, with the keyword static the variable is defined as a static global variable.

Feature: A, the variable allocates memory in the global data area. B, initialization: If not explicitly initialized, it will be implicitly initialized to 0.

  Static Local Variables

Definition: Static local variables are defined when the static keyword is preceded by a local variable.

Feature: A, the variable allocates memory in the global data area.   B, initialization: If not explicitly initialized, it will be implicitly initialized to 0. C, it always resides in the global data area until the program has finished running. But its scope is a local scope, and when the function or statement block that defines it ends, its scope ends.

  static data members
Characteristics:

A, memory allocation: Allocated in the program's global data area.

B, initialization and definition: A, static data member definition to allocate space, so can not be defined in the class declaration.     b, to avoid duplication of definitions in multiple source files that use the class, it cannot be defined in the header file of the class. c, static data members are required to exist because the program starts running, so the best place to initialize it is implemented inside the class.

C, features a, the effect on the Public,protected,private keyword it is the same as a regular data member, B, because its space is allocated in the global data area and belongs to all objects in this class, so it is not a specific class object and its scope is visible when the class object is not generated, i.e. When an instance of the class is not generated, we can manipulate it.
D, Access form A, class object name. static data member name

    E, static data members, mainly used on properties owned by all instances of the class. For example, for a deposit class, the account number is different from each instance, but the interest is the same for each instance. Therefore, interest should be set as a static data member of the deposit class. This has two advantages, first, regardless of how many deposit objects are defined, the interest data members share the memory allocated in the global area, so save storage space. Second, once the interest needs to change, as soon as the change is made, the interest of all the deposit objects changes over, because they are actually sharing one thing.  

  Static member functions
Features: A, static member functions are associated with the class, and are not associated with the object of the class. B, static member functions cannot access non-static data members. The reason is simple, non-static data members belong to a particular class instance.
Function: Used primarily for the operation of static data members.

Call form: A, Class object name. static member function name ()

The example and analysis of static statically variable, the code is as follows:

Class program
    {
        static int i = Getnum ();
        Int J = Getnum ();

        static int num = 1;

        static int Getnum ()
        {return
            num;
        }

        static void Main (string[] args)
        {
            Console.WriteLine ("I={0}", i);
            Console.WriteLine ("J={0}", new Program (). j);
            Console.read ();
        }

    

Analyze the above code:

Console.WriteLine ("I={0}", i);

Here I is the static variable, and when class program is first loaded, allocate memory for all the static variables in the program. Although there is hyper-Threading technology Now, the instructions are logically or sequentially top-down, so the static int i is allocated memory, and the default value of 0 is maintained in that memory, then the static int num variable is allocated memory, and the value is of course 0.

Then the second step is to assign a value to the variable: first the static int i variable assignment, i=getnum (), see Getnum () Inside the code, is return num, this time num value is 0, so i=0. Then assign value to the variable num, num=1, and after this line of code executes, NUM is 1. So, j=1.

So the final result is:

I=0 j=1

  Note:

When the class is first loaded, the static variables in the class are allocated the memory space sequentially, and after all the memory space is allocated, the static variables are assigned in order.

The first is divided into two parts registers and memory (including caching)

Memory is divided into two parts of code and data

Data is divided into two-part static storage and run-time storage

Runtime storage is divided into stacks and heaps
Static storage is divided into global static storage and constants

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.