Value types, reference types, and generics in previous lifetimes

Source: Internet
Author: User
Value types, reference types, and generic multi-language

Let's talk about the topic first. The CLR supports multiple languages.. NET has a very powerful feature, that is, cross-language, support many languages, such as C #, J # and so on. Let's take a look at the first picture.

    C#      J#          VB          等等等                              C#编译器   J#编译器   VB编译器       编译器                                  ---------------------------------    |           中间语言                |    ---------------------------------                              编译(运行)                            机器语言

See this diagram, each language has its own compiler, through the first compilation, compiled into intermediate files (DLL or EXE file). When the program is running, compile the intermediate file into machine language again.

But does the CLR support so many languages to be a problem? In other words, why does the CLR support so many languages?

Like a Sichuan people and a Henan dialogue, mutual understanding, but, they are two people speak Putonghua can communicate. In the CLR, each language is the equivalent of people in every place, and it is difficult to communicate with each other, but with the standard of Mandarin (the CTS (common language type) and the CLS (Common Language Specification), it is possible to speak. CTS is equivalent to our Mandarin syllables, and CLS is equivalent to the agreed grammar of Mandarin. In this way, the. NET family is formed. In the CTS, it is the value type and the reference type

Process Thread memory space

Originally wanted to clean up the process and the thread, and then want to and stack simple to say better

In one application, it allocates a process and a maximum of 4G of memory space, which is divided into 4 extents, the global data area, the code area, the thread stack area, and the managed heap area.

(Threads are the smallest unit of program run, the threads are isolated, under window, each program will have the main process, the allocation of the maximum content of 4G)

The entire project is running in this process. In this process, there may be many threads, each of which allocates a 1M managed stack space under the stack.

Global Data area: Holds global variables, static data, constant code area: store all the program code thread stack area: The local variables, parameters, return data that are allocated for running,  Return address managed heap area: Free Storage--------------------------------------------------------------------------------|  ----------------------------------------      --------------------          ||   |      ----      ---       ---      ----  |                  |          |  ||   |      | line |      | line |      | line |  | line |      |                  |          |  ||   |      | process |      | process |      | process |  | process |      |                  |          |  ||   |      |       |2|      |3| |  3|      |    |          Managed Heap |  ||   |      ----      ---       ---      ----  |                  |          |  ||       |      (The number of threads depends on your code) |                  |          |  ||         |      Thread Stacks |                  |          |  | |                                                                              ----------------------------------------      --------------------          ||                                                               ||               ||  -------------------------------   -----------------------------------       ||                             |   |                                 |       |  ||     |   Global Data Zone |          |       Code Area |  ||                             |   |                                 |       |  ||                             |   |                                 |       |  || -------------------------------   -----------------------------------       |-------------------------------------------- ------------------------------------
Value types and reference types

In C #, in general, a value type exists where it declares that the reference type exists on the managed heap. Value type conversion reference type is called boxed, reference type conversion value type is called unboxing

Value type
对于值类型的实例,CLR在运行时有两种分配方式:(1) 如果该值类型的实例作为类型中的方法(Method)中的局部变量,则该实例被创建在线程栈上;(2) 如果该值类型的实例作为类型的成员,则该实例作为引用类型(引用类型在GC堆或者LOH上创建)的实例的一部分,被创建在GC堆上
Reference type
对于引用类型的实例,CLR在运行时也有两种分配方式:(1) 如果该引用类型的实例的Size<85000Byte,则该实例被创建在GC(Garbage Collection)堆上(当CLR在分配和回收对象时,GC可能会对GC堆进行压缩);(2) 如果该引用类型的实例的Size>=85000byte,则该实例被创建在LOH(Large Object Heap)上(LOH不会被压缩)。

Speaking of here, the bedding is OK, there is a question: in the case of multi-threaded, the definition of a structure structobj, which has an int type of variable x, also defines a class classobj, which also has an int type of variable x.

        ClassObj r1 = new ClassObj();//在堆上分配        StructObj v1 = new StructObj();//在栈上分配        r1.x = 5;//根据地址找到引用类型,进行修改        v1.x = 5;//在栈上修改        ClassObj r2 = r1;//只复制引用        StructObj v2 = v1;//在栈上分配空间并复制成员        v2.x = 6;        r2.x = 6;        Console.WriteLine("v2.x=" + v2.x);        Console.WriteLine("r2.x=" + r2.x);        Console.WriteLine("v1.x=" + v1.x);        Console.WriteLine("r1.x=" + r1.x);        Console.WriteLine(r1.Equals(r2).ToString());        Console.WriteLine(v1.Equals(v2).ToString());

What is the printing result now? The answer is:

Let's take a picture to understand.

    线程堆栈                托管堆        r1-------|                      v1.x=5   |------R=6(r2重新赋值前这个值为5)        r2-------|        v2.x=6

Drawing of the comparative abstraction, R1 is a reference type, r1 the value of the existence of the declaration of his place, on the stack is the address of the managed heap, the assignment r1.x=5,v1.x=5 again instantiated, Structobj was stored in the place where he declared, and on the stack opened up a space storage x= 6,R2 instantiation just copy the reference, once again assign the value will overwrite the original 5, then the r1.x and r2.x values will be equal, say the point is R1 and R2 is a thing.

Then R1 will be exactly equal to R2 (value, address, and so on) comparison value types will only compare their values for equality, so false

If still do not understand, this can also blame me (you have the ability to beat me)

An interesting question came to mind: Why would a reference type be a score type?

Value types and reference types already exist long before C # appears. To say, it should also be a kind of helplessness. In the application under window, under the assumption that there are four threads in an application, each thread allocates a 1M of space, then 4 threads are 4M of space. First came a 1.2M of the package into the, and a 1.2 of the package has been stored in, now came a 3M packet found insufficient, this is he will not open up new space, may have released a 1.2 package is still not in. This is where memory fragmentation is generated. If you use all of the data as the value type, the thread stack area will quickly fill up and drop a lot of memory fragments to slow down the server. So I put large data on the managed heap, and on the thread stack I kept an address where I kept the data on the managed heap, and the value type was small data that was used when the thread was running, so it was on the threading stack. There may be a lot of things in the reference type, the data is larger, there is a managed heap

Now we'll talk about packing and unpacking.

Decoration is a process of converting a value type to object and then storing the wrapped object on the heap. The unboxing is a conversion from object to value type, and the object is checked first, ensuring that he is a boxed value of the given value type. Copy the value into the new value type, releasing the current object in this case, both boxing and unpacking require a large amount of CPU computation

arrays, ArrayList, generics

Arrays are supported by most languages, with the advantage that they are stored continuously, so his index speed is very fast, and the assignment and modification elements are simple and access is faster. The disadvantage is that the array is fixed, and it needs to know its size when it is created. and inserting data and deleting it is laborious. As opposed to arrays, ArrayList solves the problem of data and can be used to insert data and delete it flexibly. Because the ArrayList is not strict with the data type, when added, the object type is used to accommodate the added objects, there will be packing and unpacking operations, as a result of performance loss.

To solve this problem, Microsoft introduced the generic collection list, as follows

List<int> list=new List<int>();

As you can see, you have specified a type when defining a generic collection.

Because generics specify a type, the value is limited to the qualified type when it is accessed. This avoids the performance problems that are consumed by packing and unpacking, and improves security at the same time.

And then we'll talk about generics, and here's what you need to specifically note is that generics cannot be directly referred to as a value type or a reference type, but rather a specified type.

In the general work, often encounter generic code, I do not need to care about what type of you, you send me what type I deal with what type, or you need what type I give you what type. Like what:

public class Www<T> where T: ClassObjP{    public Www()    {    }}

Here, t denotes any type, but T is just a symbol, not a keyword, write a, B, Z, etc. can be. CLASSOBJP represents the class of the contract, the scope of the prescribed class (and the son of this class), the class that follows the principle of historical substitution (forgiving oneself for expressing ability)

Well, that's a lot to sum up. And now the end is expanding.

Covariant inversion

The above has just passed a moment in the constraints, but also mention the history of the replacement principle, and in the work, we are very small may encounter some because did not follow the Richter replacement principle of the code to error, here may be used to get covariant inversion

From the use of: covariant is a subclass to the parent class, can only be used in the output parameters out, the inverter is the parent class, can only be used in the input parameters

In usage, covariance can be used, inversion can be used, and covariance and contravariance can be used as auxiliary

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.