Description of use of static statically variable in C #

Source: Internet
Author: User
Tags constructor instance method modifier static class



Using 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.




Characteristics:
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.




Characteristics:
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 cannot be defined in the class declaration.
b, to avoid duplication of definitions in multiple source files that use the class, it is not possible in the header file of the class
Defined.
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 impact on the Public,protected,private keyword it's the same as regular data members,
b, because its space is allocated in the global data area, it is shared by all objects of this class, so it is not a particular class object and its scope is visible when no class object is generated, that is, we can manipulate it without producing an instance of the class.



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



Characteristics:
A, static member functions are associated with classes and are not associated with objects 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.



Role:
is primarily used for operations on static data members.




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






An example and analysis of static statically variable



Instance:




C # code replication


The code is as follows
Using System;

Namespace Teststatic
... {
class Class1
... {
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 Class1 (). j);
Console.read ();
}
}
}


Now analyze the above code:



Console.WriteLine (String. Format ("i={0}", i)); Here I is the static variable, and the class Class1 is the first time to be referenced, to first allocate memory for all the static variables in Class1. Although there is hyper-Threading technology Now, the instructions are executed sequentially in logic or one by one, so the static int i is first allocated memory, and the default value of 0 is maintained in that memory, and then the value of the static int num variable is then allocated to memory, of course, 0.



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



So the final result is:



I=0 j=1






Look at the following practice:





The code is as follows

Class Program
{
static void Main (string[] args)
{//output undefined static variable, the result is 0; it also shows that the variable system with no initial value in C # is automatically assigned 0
Console.WriteLine (SORT.I);
Static variable access method (class name. Static variable name), but also can operate static variables externally, visible static variables are not mysterious;
SORT.I = 5;
Output 5
Console.WriteLine (SORT.I);
You can also use the constructor to initialize the static variables, uh
Sort sorttest = new sort ();
The assignment in the output constructor is 3;
Console.WriteLine (SORT.I);
}
}
Class sort
{
public static int i;
Public sort ()
{
i = 3;
}


}




Summary: When accessing static variables inside a class, you can use the static variable name directly, not in the way of (class name. Static variable name),
In addition to static variables, there are static class instances, as well as static methods. But the usage is very similar; (No static Class Oh, hehe more silly)


The code is as follows

such as: public static void Myfun () {}//static method
private static Random myrandom=new Random (); Static class instance


It is sometimes declared as a private static variable in order for it to be initialized only once. This saves memory space
But you want it to be inaccessible outside, so use the private access qualifier to get it done.
private static: Secure and space-saving.
Example: If you want to generate a set of random numbers each time the class is instantiated, but to generate random numbers is to use a class, that is, random, this class is not a static class, it is to produce an instance, with the resulting instance to generate a random number, but if each class instantiation of the generation of a random instance, That memory space is a huge waste, so you can use:


The code is as follows
private static Random myrandom=new Random ();


So each time the class is instantiated, it uses the same random instance myrandom to generate the random number




comparison between static and non-static methods




The difference between C # static and Non-static methods is not just conceptual, so what are their specific differences? Let's give you an explanation through this article.



C # classes can contain two methods: C # static method and Non-static method. So what is the difference between their definitions? What difference do they make in using them?



Let's take a look at the most intuitive difference: the static modifier is used as the method, and the opposite is a non-static method.



Here's a four-point view of the difference between C # static and Non-static methods:



C # Static and Non-static methods compare one,
C # static Members:
① static members belong to the class, and non-static members belong to instances of the class.
② each instance of a class is created, a new piece of storage is allocated in memory for non-static members;



Static members are owned by the class and are common to instances of each class, regardless of how many instances the class creates, and the static members of the class occupy only the same area in memory.



C # Static and Non-static methods comparison Two,




C # static methods
1. C # static methods belong to all classes and can be used before class instantiation.
2. A non-static method can access any member of a class, and a static method can only access static members in a class.
3, because static methods can be used before class instantiation, and non-static variables in a class must be instantiated before memory can be allocated.



In this way, the memory address used by non-static variables cannot be judged by the C # static method invocation. So it can't be used. The address of the static variable is fixed to the class, so it can be used.



C # Static and Non-static methods comparison Three,
A C # static method is a special member method that does not belong to a specific instance of a class, but to the class itself. Therefore, it is not necessary to create an instance of a class first in a static method, but rather with the class name. The format of the static method.
The 1.static method is a member method in a class that belongs to the entire class, that is, you can call it without creating any objects!
Only static variables and other static methods can appear inside static! And the static method cannot use this .... and other keywords ... Because it belongs to the whole class!
2. The static method efficiency is higher than the instantiation, the static method disadvantage is does not automatically destroys, but the instantiation can do destroys.
3. Static methods and static variables always use the same piece of memory after creation, but using instances creates multiple memory.
There are two kinds of methods in 4.c#: Instance method, static method.



C # Static and Non-static methods comparison Four,
Get the name of the class in the C # static method
In Static methods:


The code is as follows
String className = System.Reflection.MethodBase.GetCurrentMethod (). Reflectedtype.fullname;


Non-static methods can also be used:
String className = this. GetType (). FullName;



The difference between C # static and Non-static methods is designed to interpret the meaning of the C # static method, and I hope it helps you understand and learn about C # static and Non-static methods.


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.