C # Common type system deep copy shallow copy function transfer parameter

Source: Internet
Author: User

The deep-seated representation of C # Common type systems and variables in the transfer of deep copy shallow copy functions

In the programming encountered some unexpected anomalies, tracking found that the C # variable in memory of the performance of the understanding of the deviation, the system of learning and through the code experiment to comb through the various situations, variables in memory level of the performance of the future coding should be some help. In this record to avoid forgetting ...
1. Common Type System

Take a picture first:

Common data types are divided into value types and reference types.

We define an int that is actually an instance of System.Int32, which is syntactically like using other class objects, but the underlying type is still stored. This unifies the basic type and the reference type in syntax, so it can be called

Common type System. In fact, each value type has a. NET corresponding to a system.***.

A reference type,string is a reference type . In many people, string behaves like a value type, but he is a reference type, but a regenerated string object returned by many member functions of the String class. We should use reference types as Object pointers.

When we learn C + +, we know that variables are allocated on heaps or stacks. The discussion in C # is that we are not differentiating the stack, now uniform is called the stack. C # introduces a new memory space, called the managed heap.

Referring to a diagram of someone else, the heap on the right of the graph should actually be the managed heap.

Object pointers for value types and reference types are allocated on the stack, whereas specific objects of reference types are allocated on the managed heap.

2. Variable assignment operation

Value type assignment : The assignment of a value type is simple, that is , in the stack request space, the value is written to the requested space . int a = 10; that is, the stack assigns a 4-byte space to a, 4 bytes of space holds 10 of the binary, int b =a, that is, the stack assigns 4 bytes to B, and 4 bytes of space holds the binary of the value of a, which is 10. A and B are completely independent, B just use the value of a to assign a value to their own space.

Reference type Assignment : When the reference type is declared, the stack allocates 4 bytes of space (the size of a pointer), and the initial value is 0x00000000. such as Object boxed, at which time the boxed allocates 4 bytes of space, the space is 0x00000000;boxed= new object (), at which time the managed heap is allocated space to hold an object, Boxed holds the first address of the object on the managed stack in a 4-byte space on the stack. When you use Object a =b, the stack is allocated a 4-byte space of a, whose value is the value of the 4-byte space of B. A, B saves the same address value, pointing to an object in the same managed heap. A, B is just a different "pointer" to the same object.

3. Shallow copy and deep copy of reference type

Shallow copy and deep copy problems occur when the object contains a member of a reference type in this case. Plainly, shallow copies and deep copies have no space to reassign to the object's reference type members. The reference type object is stored in the managed heap, and if the object itself contains a member of a reference type, this member stores the address of the member object of the reference type in the object. Understanding that "I" contains a pointer to a "he", you want to shallow copy me, I give this pointer to you, you also point to "he"; when you want to copy me deep, create a "his" brother that uses new, and you point to "his" brother that is new's return value (address).

The example illustrates the following:

 classProgram {Static voidMain (string[] args) {Test a=NewTest ("AAA",Ten); Test b=A; Test C=A.clone (); C.myint= -; C.mystr="BBB"; C.myintclass.myint= +; Console.WriteLine (A.myint+"    "+ a.mystr+"    "+a.myintclass.myint); Console.WriteLine (B.myint+"    "+ B.mystr +"    "+b.myintclass.myint); Console.WriteLine (C.myint+"    "+ C.mystr +"    "+c.myintclass.myint);        Console.ReadLine (); }    }     Public classTest:object { Public stringmystr {Get;Set; }  Public intmyInt {Get;Set; }  PublicIntclass Myintclass {Get;Set; }  PublicTest Clone () {return(Test) This.        MemberwiseClone (); }         PublicTest (string_STR,int_int) {mystr=_str; MyInt=_int; Myintclass=NewIntclass (_int); }    }     Public classIntclass { Public intmyInt {Get;Set; }  PublicIntclass (int_int) {MyInt=_int; }    }

A and B are references to the same test object, and C is a shallow copy of a, where C points to an int, a pointer to a string (the same value as a pointer to string), A pointer to Intclass (the same as the value of a pointer to Intclass). When changing the int of C, A is not affected, and when the Intclass of C is changed, the same object that A,c points to is changed, so the intclass of A,b,c is changed at the same time. There is an interesting phenomenon, that string is also a reference type, and C changes its mystr,a to be affected by the confiscation. This is a special indication that the string is a special reference type,

C.MYSTR = "BBB"; in fact, re-created a string object, C's mystr point to the new object, so a is not affected. The string object is not changed, and any action on the string is made on a new object, and then a new object reference is returned. so many times string behaves more like a value type, although it is indeed a reference type.
4. Function parameters

Whether a value type or a reference type, the function default is passed as a value, and the parameter is "copy" the value of the argument. a good understanding of value types is that the parameters are assigned new space on the stack, and the values of the arguments are copied into the newly allocated space. For reference types, the parameter is assigned a new space on the stack, the value of the argument-the argument is copied into the newly allocated space in the 4-byte object address of the stack hold, and the object is not created on the managed heap. All , the reference type passed by the function, the real participation parameter is a different space on the stack, but the object it points to is the same.

Example:

Test a = new test ("123", 10);
Console.WriteLine (a.myint + "+ a.mystr +" "+ a.myintclass.myint);
int b = 100;
Change (A, b);
Console.WriteLine (a.myint + "+ a.mystr +" "+ a.myintclass.myint);
Console.WriteLine (b);

public static void Change (Test _test,int _int)
{
_test.myint = _int;
_int *= 10;
}

after function cha the Nge after the myint of object a becomes 100, and the value of B of type int does not change or 100.

It is simple to assume that the value passing of a function is limited to the allocation space on the stack and to the assignment of new space.
Out and ref :
C # functions have out and REF2 keyword adornments. Let's talk about Ref,ref equivalent to & in C + +. ref also does not allocate space on the stack, and formal parameters and arguments are a space on the stack. any change to a formal parameter is reflected in the argument, and even changes to the object that the parameter points to are reflected on the argument. Examples are as follows:
Test A =NewTest ("123",Ten); Console.WriteLine (A.myint+"    "+ A.mystr +"    "+a.myintclass.myint); intb = -; Change (refArefb); Console.WriteLine (A.myint+"    "+ A.mystr +"    "+a.myintclass.myint);                Console.WriteLine (b);  Public Static voidChange (refTest _test,ref int_int) {_test=NewTest ("New", _int); _int*=Ten; }



The change is passed the REF keyword-decorated parameter, and any action within the change for the formal parameter is equivalent to the operation of the argument. We do not compare with the REF keyword:
Test A =NewTest ("123",Ten); Console.WriteLine (A.myint+"    "+ A.mystr +"    "+a.myintclass.myint); intb = -;            Change (A, b); Console.WriteLine (A.myint+"    "+ A.mystr +"    "+a.myintclass.myint);                Console.WriteLine (b);  Public Static voidChange (Test _test,int_int) {_test=NewTest ("New", _int); _int*=Ten; }


Without the ref keyword, an assignment operation for a reference type is not reflected on the argument, because we assign the address value on the stack of the parameter to the newly allocated object in the managed heap. The address value on the argument stack still points to the old object. Without ref arguments, the parameters are 2 different spaces on the stack.

The Out keyword, like ref, is the same stack address as the form participation argument, and the out parameter must be assigned a value (that is, a new object is allocated on the managed heap) before the function exits.

summary function Parameters:

By default, it refers to passing, allocating space on the stack, and copying the corresponding value on the stack to the newly allocated space. Operations on the parameter stack (assignment of value types, assignment of reference types) are not reflected on the arguments. The operation on the managed heap (the member that changes the reference type) is reflected on the argument.
Ref is passed, and no new space is allocated on the stack, and formal parameters and arguments are the same stack address. an action on the parameter stack (assignment of a value type, assignment of a reference type) and an operation on a managed heap (a member that alters a reference type) is reflected on the argument.
Out passes, no new space is allocated on the stack, and formal parameters and arguments are the same stack address. The parameter must be assigned a value before the function returns.

C # Common type system deep copy shallow copy function transfer parameter

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.