Reprint static and non-static class comparisons in C #

Source: Internet
Author: User
Tags terminates

Reprint Original Address: http://www.cnblogs.com/NothingIsImpossible/archive/2010/07/28/1786706.html

The difference between C # static and non-static methods is not only conceptual, but what are their specific differences? Let's make a resolution to you through this article.

C # classes can contain two methods: C # static and non-static methods. So what is the difference in their definition? What is the difference in their use?

Let's take a look at the most intuitive differences: The static method is used with the static modifier, and the inverse is a non-static method.

Let's look at the difference between a C # static and a non-static method in four ways:

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

Static members are owned by the class and are common to instances of each class, regardless of how many instances the class creates, and 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 are class-owned and can be used before class instantiation.
2. Non-static methods can access any member of the class, and static methods can only access static members in the class.
3. Because static methods can be used before the class is instantiated, non-static variables in the class must be instantiated before the memory is allocated.

In this way, C # static method calls cannot determine the memory address used by non-static variables. 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 of three,
A C # static method is a special member method that is not part of a specific instance of a class, but rather belongs to the class itself. Therefore, the static method does not need to create an instance of a class first, but instead takes 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 directly without creating any objects!
Static variables and other static methods can only appear inside static! And this is not available in the static method .... and other keywords. Because it belongs to the whole class!
2. Static methods are more efficient than instancing, and the disadvantage of static methods is that they are not destroyed automatically, while instantiated can be destroyed.
3. Static and static variables always use the same piece of memory after they are created, and the way the instance is used creates multiple memory.
There are two methods in 4.c#: Instance method, static method.

C # static and non-static methods of comparison four,
Get the name of a class in C # static method
Static methods:
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 interpreted to explain the meaning of C # static methods, and it is hoped to help you understand and learn C # static and non-static methods.

Reprint http://www.cnblogs.com/linuxnotes/archive/2013/05/24/3096145.html

Static class

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

Static classes are introduced from C # 2.0, and C # 1.0 does not support static class declarations. The programmer must declare a private constructor. A private constructor prohibits a developer from instantiating an instance of a class outside the scope of the class. The effect of using a private constructor is very similar to the effect of using a static class.

The difference between the two:
Private constructors can still instantiate classes from within the class, while static classes prohibit the instantiation of classes from anywhere, including from within the class itself. Another difference between static classes and the use of private constructors is that in classes that use private constructors, instance members are allowed, whereas C # 2.0 and later compilers do not allow any instance members of static classes. 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 will guarantee that instances of this class will not be created. Another characteristic of a static class is that the C # compiler automatically marks it as sealed. This keyword specifies that the class is not extensible, in other words, you cannot derive other classes from it.

Key features of static classes:
1: Contains only static members.
2: Cannot instantiate.
3: Is sealed.
4: Cannot contain instance constructors.

Static members
1: A non-static class can contain static methods, fields, properties, or events;
2: No matter how many instances are created on a class, its static members have only one copy;
3: Static methods and properties cannot access non-static fields and events in their containing types, and cannot access instance variables of any object;
4: Static methods can only be overloaded, not overridden, because static methods do not belong to instance members of the class;
5: Although a field cannot be declared as static const, the behavior of a const field is inherently static. Such a field belongs to a class and does not belong to an instance of the class. Therefore, you can use classname.membername notation to access a const field as you would with a static field; 6:c# does not support static local variables (static variables are defined inside a method).

Static constructors
1: Static classes can have static constructors, static constructors are not inheritable;
2: Static constructors can be used for static classes, or for non-static classes;
3: Static constructors No access modifiers, no parameters, only one static flag;
4: Static constructors cannot be called directly, and static constructors are executed automatically and only once when a class instance is created or any static member is referenced.

Attention:
1: Static class in memory is always a position;
2: Non-static class after instantiation is in memory is independent, its variables will not repeat, after use will be destroyed in time, so there will be no unknown error. Static members in C # are relatively sensitive and should not be used without being very sure;
3: It is recommended to use more general classes (non-static classes).

Use selection:
When the defined class does not need to be instantiated, we use static classes, and if you need to instantiate an object, you should use a non-static class when you need to inherit attributes such as, and the uniformly used variables and methods are set to static, then all instance objects can be accessed.

A summary of learning about static members and methods in C #

Data members:
Data members can be divided into static variables, instance variables, and two.
Static members: Static member variables are associated with a class and can be used as a "common" variable in a class (a commonality of expression), and he does not rely on the existence of a particular object, accessed by the name of the multibyte variable when it accesses the class name.

Instance member: an instance member variable is associated with an object, and accessing an instance member variable depends on the existence of the instance.

Function Members:
Methods can be mainly divided into static methods, example methods

Static methods: Static methods are methods that are not part of a particular object, static methods can access static member variables, static methods can not directly access instance variables, and in the case of instance function calls, instance variables are passed as arguments to static methods. A static method cannot invoke an instance method directly, it can be called indirectly, first to create an instance of a class, and then to invoke a static method through this particular object.

Instance method: The execution of an instance method is associated with a particular object, and his execution requires an object to exist. Instance methods can directly access static variables and instance variables, and instance methods can directly access instance methods, and static methods, and static methods access the multibyte variable names for the class name. When multiple instance objects exist, there is not a copy of a particular instance method in memory, but all objects of the same class share a copy of each instance method (the instance method occupies only a "set" of space).

If a member in a class is declared as static, the member is said to be a statically member. In general, static members are owned by the class, and non-static members belong to instances of the class. Every instance of creating a class creates an area in memory for non-static members. The static members of the class are all classes, shared for all instances of the class. No matter how many copies this class creates, a static member occupies only one area of memory.

The life cycle of static member variables in C # classes is when to create and when to destroy the "lifetime" of a declared element is the time period in which the element is available for use. A variable is the only element with a lifetime; for this reason, the compiler treats procedure parameters and function return values as special cases of variables. The lifetime of a variable indicates the time period at which it can retain a value. The value of the variable can be changed during the lifetime, but the variable always retains some value.

A different life cycle

Variables declared at the module level are usually present during the entire run of the application. A non-shared variable declared in a class or struct exists as a separate copy of each instance of the class or struct in which it is declared, and each such variable has the same lifetime as its instance. However, the Shared variable has only one lifetime, which is the total time that the application runs.

Local variables declared with Dim exist only when the procedure that declares them is executing. The same applies to the parameters of the procedure and any function return values. However, if the procedure calls other procedures, local variables retain their values while the called procedure is running.

The beginning of the life cycle

When you execute a procedure that declares a local variable, the lifetime of the local variable begins. As the procedure starts, each local variable is initialized to its default value for the data type. numeric variables (including Byte and Char) are initialized to the 0,date variable initialized to zero January 1 of A.D. 1, the Boolean variable is initialized to False, and the reference type variable (including string, array, and Object) is initialized to nothing.

Each member of a struct variable is treated as a separate variable initialization. Similarly, each element of an array variable is initialized separately.

If a variable is declared with an initializer, the variable is assigned the specified value when it executes the declaration statement for the variable, as shown in the following example:

Dim X as Double = 18.973 ' x had previously been initialized to 0.
A variable declared in the inner block of a procedure is initialized to its default value when it enters the procedure. These initializations will take effect regardless of whether the block has been executed.

The end of the life cycle

When the procedure terminates, the local variable value of the procedure is no longer preserved, and the memory used by the local element is reclaimed. The next time the procedure is executed, all its local elements are recreated and the local variables are initialized.

When an instance of a class or struct terminates, its non-shared variables lose their value. Each new instance of a class or struct creates all of its non-shared elements and initializes non-shared variables. The Shared element is persisted until the application stops running.

Extension of life time

If a local variable is declared with the Static keyword, its lifetime is longer than the execution time of the procedure that declares it. If the process is within a module, the static variable persists as long as the application continues to run.

If the static variable is declared in the inner procedure of the class, the lifetime of the variable depends on whether the procedure is shared. If this procedure has been declared with the shared keyword, the lifetime of the variable will continue until the application terminates. If this procedure is unshared, its static variable is an instance member of the class, and its lifetime is the same as the lifetime of the class instance.

In the following example, the RunningTotal function calculates the total of traffic by adding a new value to the total of the previous value stored in the static variable ApplesSold:

Copy Codecode example: Function runningtotal (ByVal Num As Integer) As Integer
Static ApplesSold as Integer
ApplesSold = ApplesSold + Num
Return ApplesSold ' ApplesSold keeps its current value.
End Function

If ApplesSold is declared without Static, the previously accumulated value is not preserved during the function call, and the function returns only the same value that was last used to invoke it.

Declaring ApplesSold at the module level can produce the same lifetime. However, if you change the scope of the variable in this way, the procedure will no longer have exclusive access to the variable. Because other procedures can access the variable and change its value, the traffic totals are unreliable, and the code can be more difficult to maintain.

Static members are initialized before being accessed for the first time and before any static constructors, such as calls. To access a static class member, you use the class name instead of the variable name to specify the location of the member.

Reprint static and non-static class comparisons in C #

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.