[You must know. NET] Return Ninth: taste type-value type and reference type (medium)-rule is boundless

Source: Internet
Author: User
Continue to focus on the value type and reference type topics.

This article introduces the following:

  • Basic concepts of Types
  • In-depth Value Type
  • In-depth reference type
  • Comparison and Application of Value Type and reference type

1.Introduction

The release of the last [eighth back: taste type-value type and reference type (top)-memory rational] has attracted a lot of attention, from the memory perspective, we understand why the value type and the reference type, and the task left behind is, of course, how the different characteristics of the application type play a role in system design, performance optimization, and other aspects. Therefore, this is a powerful supplement to the previous round. At the same time, we should try our best to focus on some design analysis from the perspective of memory debugging, this will help you thoroughly and comprehensively understand this topic. Of course, this is also the focus of the next session.

From the perspective of memory, we can discuss that value types and reference types are rational, while from the perspective of rules, we can understand that value types and reference types are boundless. The purpose of this article is to thoroughly integrate the topic from the perspective of the above echo. the boundless application is still from the capricious practice. Therefore, I can only explain my views from one angle, however, it is certainly impossible to make a global effort. Therefore, we will discuss the application fields of the value type and the reference type from the following perspectives.

2.General rules and Comparison

General rules:

  • String is a special reference type that inherits from System. the Object must be a reference type, but the value type is highlighted in the application performance. Why? For example, an example is as follows:

 

Simply put, because of the immutable feature of the string, every change to the string will generate a new string variable in the managed heap. When the above string is passed as a parameter, in fact, when the s = s operation is executed, a new space is generated in the managed heap and data is copied. Therefore, a result similar to passing by value is returned. However, according to our memory analysis, we can see that string is still a reference type in nature, and it is generated by address when passing parameters. However, due to its special constant characteristics, A New string object is created inside the function and Initialization is completed. However, this change cannot be obtained outside the function. Therefore, the external function is similar to passing by value. As for the special interpretation of the string type, I recommend Artech's masterpiece "a deep understanding of string and how to use string efficiently".

In addition, the = Operator is overloaded for the string type. In the type comparison, the actual string is compared, rather than the reference address. Therefore, the following execution results are available:

String aString = "123 ";
String bString = "123 ";
Console. WriteLine (aString = bString); // It is displayed as true, equivalent to aString. Equals (bString );
String cString = bString;
C string = "456 ";
Console. WriteLine (bString = cString); // The value is false, which is equivalent to bString. Equals (cString );

  • Generally, you can use Type. IsValueType to determine whether the Type of a variable is a value Type. The typical operation is:

Public struct MyStructTester
{}

Public class isValueType_Test
{
Public static void Main ()
{
MyStructTester aStruct = new MyStructTester ();
Type type = aStruct. GetType ();
If (type. IsValueType)
{
Console. WriteLine ("{0} belongs to value type.", aStruct. ToString ());
}

}
}

  • .. NET uses the ref and out operators to identify the value type passed by reference type. The difference is that ref must be initialized before the parameter is passed, and out does not need to be initialized before the parameter is passed, the value must be explicitly assigned during transmission.
  • The conversion process between the value type and the reference type is referred to as packing and unpacking, which deserves our special discussion. Therefore, we will leave this topic to be discussed in detail later.
  • The sizeof () operator is used to obtain the size of the value type, but is not applicable to the reference type.
  • The Value Type uses the new operator to complete initialization, for example, MyStruct aTest = new MyStruct (). The initialization action is not completed for a single pure definition, and reference to Members cannot be compiled, for example:

MyStruct aTest;
Console. WriteLine (aTest. X );

  • The performance of the reference type is less than that of the value type mainly because of the following: the reference type variable should be allocated to the hosting stack; the memory release should be completed by GC, resulting in a certain CG heap pressure; at the same time, the memory allocation process and object access problems of the attached Members must be completed. Therefore ,. the NET system cannot be ruled by pure reference types, and the value types with better performance and space and ease of management have a place, in this way, we will not perform complicated memory allocation and release work because of a simple byte type. Richter refers to the value type as a "lightweight" type, which is just like this. When the data is small, the value type should be given priority.
  • All value types are inherited from System. valueType, while System. valueType inherits from System. object. The main difference is that ValueType overrides the Equals method to compare the value type by instance value rather than the reference address. Specifically:

Char a = 'C ';
Char B = 'C ';
Console. WriteLine (a. Equals (B); // true is returned;

  • Primitive types are directly supported by the compiler. The concept is actually for specific programming languages, such as C # Or VB. NET, usually for applications. NET Framework. This is a conceptual boundary and cannot be confused. For example, int corresponds to System. Int32 and float corresponds to System. Single.

To learn more, see:

  • The Value Type inherits from ValueType (Note: System. ValueType inherits from System. Object), and the reference type inherits from System. Object.
  • A value type variable contains its instance data. Each variable stores its own data copies. Therefore, by default, parameter passing of the value type does not affect the parameter itself; the reference type variable stores the reference address of its data. Therefore, when passing parameters in reference mode, the parameter itself is affected because the two variables reference the same address in memory.
  • There are two types of values: binning and unboxing. The reference type can only be boxed. I will discuss this topic in detail in the next section.
  • Typical value types include struct, enum, and a large number of built-in value types. classes can be referred to as reference types. For the main differences between struct and class, refer to my role for "back-to-back: class and struct" to learn more. It is also a powerful supplement to the application of value types and reference types.
  • The memory of the value type is not controlled by GC (garbage Collection, Gabage Collection). When the scope ends, the value type is released independently, reducing the pressure on the managed heap. Therefore, it has a performance advantage. For example, struct is generally more efficient than class, and GC is used to recycle reference-type memory. Microsoft even recommends that you do not release the memory on your own.
  • The value type is sealed. Therefore, the value type cannot be a base class of any other type, but can be a single inheritance or multiple inheritance interfaces. The reference type generally has inheritance.
  • The value type does not have polymorphism, but the reference type does.
  • The Value Type Variable cannot be null, and the value type is initialized to 0. By default, the reference type variable is created as null, indicating that it does not point to any reference address of the managed heap. An NullReferenceException is thrown for any operation of the reference type whose value is null.
  • The value type has two statuses: boxed and unboxed. The runtime provides the boxed form of all value types, while the reference type usually has only one format: boxed.

3.Remedies-application scenarios and precautions

Now, based on the knowledge of the memory mechanism and general rules, we can well summarize how to choose the value type and reference type during system design? Of course, our focus is to tell you how to choose the value type, because the referenced class type is the main body of. NET, and you can win the market without too much attention.

3.1Value Type application scenarios

  • In MSDN, we recommend that you use the type size as the decisive factor for selecting the value type or reference type. When the data is small, it is best to consider the value type to improve the system performance;
  • The value type is a good choice when the structure is simple and there is no need for Polymorphism;
  • The nature of a type does not represent travel time and does not need to be implemented by classes. In the case that data is stored as the primary object, the value type is the preferred choice;
  • When passing parameters, the value type transmits instance data by default, rather than the memory address. Therefore, the selection of data transmission depends on the internal implementation logic of the function. The value type can be supported by efficient memory, and a copy of instance data is returned without exposing the internal structure. You can consider the value type for security, however, excessive value transfer will also damage performance optimization. you should choose the appropriate value;
  • The value type has no inheritance. If the selection of the type does not require subclass inheritance, the value type is prioritized;
  • In a set or queue that may cause packing and unpacking operations, the value type is not a good choice, because it will cause the packing operation of the value type, resulting in additional memory allocation, for example, in Hashtable. I will focus on this in subsequent topics.

3.2Application scenarios of reference types

  • In short, the reference type is. NET, we can say. the NET world is composed of classes. Classes are basic concepts of object-oriented and basic elements of the program framework. Therefore, flexible data encapsulation makes reference types mainstream;
  • The reference type is applicable to scenarios with complex structures, inheritance, polymorphism, and outstanding behavior;
  • Parameter transmission is also a necessary factor;

4.Reargument type determination, etc.

Types include Equals (), ReferenceEquals (), and = /! = Three common methods, the core of which is Equals. We know that Equals is System. the virtual method provided by the Object to compare whether two objects point to the same reference address ,. many types of NET Framework have implemented rewriting of the Equals method, for example, the value type's "ancestor" System. valueType loads the Equal Method to Determine instance data. Therefore, the determination of types should also be analyzed from different situations such as rewriting or overloading Equals, and the determination of value type and reference type. The three methods are different, so pay more attention to them.

4.1Value Type Determination

  • Equals and System. ValueType reload the Equals method of System. Object to determine instance data.
  • ReferenceEquals. If ReferenceEquals is applied to the value type, false is always returned.
  • =, The value type of = that is not overloaded will compare whether the two values are equal by bit.

4.2Reference Type determination, etc. 

  • Equals. There are two main methods:

Public virtual bool Equals (object obj );
Public static bool Equals (object objA, object objB );

One is a virtual method. The default value is the reference address comparison. The static method, if objA is an instance of the same as objB, or if both are empty references, or if objA. if Equals (objB) returns true, it is true; otherwise, it is false .. Most classes in. NET override the Equals method. Therefore, the return value of the criterion must be determined based on the specific rewriting conditions.

  • ReferenceEquals, static method, can only be used for reference type, used to compare whether two instance objects point to the same reference address.
  • =, The default value is the reference address comparison, which usually implements the = overload. The reference type of = is not overloaded to compare whether two objects are cited addresses, it is equivalent to the Equals method of the reference type. Therefore, many. NET classes implement the overload of the = Operator. For example, the = Operator of System. String is used to compare whether two strings are the same. The main difference between the = and equals methods is that the polymorphism is manifested as being overloaded, while the Equals method is rewritten.

It is necessary to rewrite or re-load Equals and = in a custom type to improve performance and targeted analysis.

5.Type conversion

Type conversion is one of the important factors that cause system exceptions. Therefore, it is necessary to make a simple summary in this topic. We do not want to take full care of it, but follow the outline. Common conversions include:

  • Implicit conversion: the conversion process of high-level types of low-level items. It mainly includes implicit conversion of value type, implicit conversion of basic types such as numerical type, implicit conversion of reference type, and conversion of derived classes to the base class; the conversion of value type and reference type refers to the conversion of packing and unpacking.
  • Display conversion: Also called forced type conversion. However, the conversion process does not guarantee data integrity, which may cause loss of precision or unknown exceptions. The conversion format is,

(Type) (variable, expression)

For example: int a = (int) (B + 2.02 );

  • Packing and unpacking of value and reference types is the most important type conversion in. NET. Improper conversion operations will cause significant performance loss. Therefore, we will discuss it with a special topic.
  • Use the "is" and "as" operators to perform type-Based Secure conversion. For more information, see "First: resentment: is and as".
  • The System. Convert class defines convenient implementation for basic type conversion.
  • All types except string have the Parse method, which is used to convert the string type to the corresponding basic type;
  • Using explicit or implicit to convert user-defined types mainly improves the implementation method of user-defined type conversion to achieve more objective conversion operations. The conversion format is,

Static access modifier operator conversion modifier operator type (parameter list );

For example:

Public Student
{
//

Static public explicite opertator Student (string name, int age)
{
Return new Student (name, age );
}

//
}

All conversions must be static.

6.Conclusion

Now, we have extended the Analysis of the Value Type and reference type from several angles. As mentioned at the beginning of this article, there are still many key points to grasp the type, however, I think it is desirable to adopt a partial solution, especially in the process of technology exploration. From the above perspectives, I think it is the only way to grasp the value type and reference type. Otherwise, in actual system development, we will often fall behind in small places and cannot figure out.

Taste type. We use the application as the key to reveal the rules and radius of value type and reference type.

Taste type, we will take the example as the navigation, start a layer of in-depth analysis, the next back to "10: taste type-value type and reference type (below) -Application Path: Goodbye.

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.