. NET Foundation Supplements (1) Type syntax basics and memory Management Fundamentals 1

Source: Internet
Author: User
Tags shallow copy

First, the underlying type and syntax 1.1. What are the base classes for all types in net?

  all built-in types in. NET inherit from the System.Object type .

1.2 What is the difference between a value type and a reference type?

The types in. NET are classified as value types and reference types, each with their own characteristics, all of which are inherited from System.Object, but the most obvious distinguishing criterion is whether they inherit from System.ValueType (System.ValueType inherits from System.Object), meaning that all types that inherit from System.ValueType are value types, while others are reference types. Common value types include: struct, enum, Integer, Float, Boolean, and so on, and all types defined in C # with the class keyword are reference types.

PS: strictly speaking, System.Object, as the base class for all built-in types, does not have a value type and a reference type. However, System.Object objects have the characteristics of reference types. This is also why value types require boxing and unpacking operations in some cases.

(1) Differences when assigning values

This is one of the most significant differences between a value type and a reference type: A variable of value type directly obtains a true copy of the data, whereas assigning a reference type is simply assigning a reference to the object to the variable, which may result in multiple variables being referenced to an object instance .

(2) Differences in memory allocation

  objects of the reference type will allocate memory on the heap, while objects of value type will allocate memory on the stack . The stack space is relatively limited, but the efficiency is much higher than the heap.

(3) Differences in inheritance structure

Since all value types have a common base class System.ValueType, value types have a common nature that some reference types do not have, and the more important thing is the comparison method of value types: Equals. All value types have implemented a comparison of content (rather than a comparison of reference addresses), whereas reference types do not override the Equals method or use reference comparisons.

1.3 The principle of packing and unpacking?

(1) Boxing: The CLR needs to do extra work to move the value type on the stack to the heap, which is called boxing.

(2) Unpacking: The counter operation of the boxing operation, the object in the heap is copied to the stack, and its value is returned.

Boxing and unpacking all imply a series of operations on heap and stack space, and there is no doubt that the performance cost of these operations is significant, especially with respect to the operation of the space on the heap, which is much slower than the stack and can cause garbage collection . These will affect the performance of the system on a large scale. Therefore, we should avoid any unnecessary packing and unpacking operations .

How to avoid it, first analyze the occasions where boxing and unpacking often occur:

① formatted output of a value type

②system.object Types of containers

For the case of ①, we can avoid the following change examples:

    int Ten ;    Console.WriteLine ("Thevalue is {0}", i.ToString ());

In the case of ②, generic techniques can be used to avoid using containers for System.Object types, effectively avoiding large-scale use of boxing and unboxing:

    New ArrayList ();    Arrlist.add (0);    Arrlist.add ("1");     // using generic data structures instead of ArrayList    list<intnew list<int>();    Intlist.add (1);    Intlist.add (2);
1.4 The difference between struct and class, where is the struct suitable for?

First,struct (struct) is a value type , and Class (class) is a reference type , and all of the struct objects are allocated on the stack, and all class objects are allocated on the heap.

Second, structs, unlike class, do not have inherited attributes , although structs can override virtual methods defined in System.Object, but cannot define new virtual and abstract methods.

Finally, a struct cannot have a parameterless constructor (class is default), nor can it define an initial value for a member variable.

     Public struct A    {        publicint1//  cannot be compiled here by    }

A struct object must be initialized to 0 at construction time, and constructing a full 0 object means allocating an appropriate space for the object in memory and placing the control at 0.

How do I use struct or class? when a type is simply a collection of raw data and does not require complex operations, it should be designed as a struct, otherwise it should be designed as a class.

1.5 How are the parameters passed for methods in C #?

(1)ref Keyword: reference passing parameters, need to be initialized before delivery , (ref requires parameters to be initialized before passing in)

(2) out keyword: reference passing parameter, need to initialize before return ; (out requires parameter to be initialized before method returns)

The functions of the two keywords, ref and out, are extremely similar, and are used to indicate that the parameter is passed in a reference manner. We all know that. NET types are reference types and value types, and when a method parameter is a reference type, the nature of the pass is the object's reference. Therefore, the effect of these two keywords occurs on the value type .

(3)params keyword: allows the method to be undefined in the number of parameters , which is very similar to array parameters, but the form is more concise and understandable.

The use of the But,params keyword also has limitations: when a method declares a params parameter, it is not allowed to have any additional parameters behind it .

For example, the following code defines two exactly equal methods: Notparams and Useparams, when using the method of the params modifier parameter, you can simply pass in all the variable collections without first declaring an array object.

    classProgram {Static voidMain (string[] args) {            //params            strings ="I am a string"; inti =Ten; Doublef =2.3; Object[] par =New Object[3] {s, I, f}; //Not use paramsnotparams (PAR); //Use paramsUseparams (S, I, f);        Console.readkey (); }        //Not use params         Public Static voidNotparams (Object[] par) {            foreach(varObjinchpar)            {Console.WriteLine (obj); }        }        //Use params         Public Static voidUseparams (params Object[] par) {            foreach(varObjinchpar)            {Console.WriteLine (obj); }        }    }
View Code1.6 Shallow copy and deep copy the difference?

(1) Shallow copy: When copying an object, simply copy all non-static type members from the original object and all references to reference type members . (The new object and the original object will share the actual object of all reference type members)

(2) deep copy: When copying an object, copy not only all non-static type members, but also the actual objects of all reference type members .

Shows the difference between shallow copy and deep copy:

In. NET, the base class System.Object has implemented shallow replication for all types, and the type is to expose a replicated interface, which is typically implemented by the icloneable interface. ICloneable contains only one method Clone, which can be implemented either as shallow copy or as deep copy, depending on the specific type of demand. In addition, in the Sys-tem.object base class, there is a protected memeberwiseclone() method, which is used for shallow copying. So, for a reference type, to achieve a shallow copy, you only need to call this method:

     Public Object Clone ()    {            return  memberwiseclone ();    }

The following code shows a simple example that uses the ICloneable interface to provide deep replication:

     Public classdeepcopy:icloneable { Public inti =0;  PublicA A =NewA ();  Public ObjectClone () {//implementing deep Replication-mode 1: Assigning and instantiating in turnDeepcopy NEWOBJ =Newdeepcopy (); NEWOBJ.A=NewA (); Newobj.a.message= This. A.message; NEWOBJ.I= This. I; returnNEWOBJ; }         Public New ObjectMemberwiseClone () {//Enable Shallow replication            return Base.        MemberwiseClone (); }         Public Override stringToString () {stringresult =string. Format ("The value of I is {0},a = {1}", This. i.ToString (), This. A.message); returnresult; }    }     Public classA { Public stringMessage ="I am the original a"; }     Public classProgram {Static voidMain (string[] args) {deepcopy DC=Newdeepcopy (); DC.I=Ten; DC.A=NewA (); Deepcopy Deepclone= DC. Clone () asdeepcopy; Deepcopy Shadowclone= DC. MemberwiseClone () asdeepcopy; //A deep copy of the target object will have its own reference type member objectDeepclone.a.message ="I'm a deep copy.";            Console.WriteLine (DC);            Console.WriteLine (Deepclone);            Console.WriteLine (); //A shallow copy of the target object will share the reference type member object with the original objectShadowclone.a.message ="I was a shallow copy of a";            Console.WriteLine (DC);            Console.WriteLine (Shadowclone);        Console.readkey (); }    }
View Code

As shown in the execution results, it is clear that the assignment of the properties of the deep copy object does not affect the original object, whereas shallow copy is the opposite.

As you can see from the above code, in the implementation of deep replication, it is too cumbersome for each object to do deep replication in such a way that the object can be deeply copied using serialization/deserialization : The object is serialized (Serialize) into memory before being deserialized, In this way, deep replication of objects is performed:

[Serializable] Public classdeepcopy:icloneable {... Public ObjectClone () {//implementing deep Replication-mode 1: Assigning and instantiating in turn//deepcopy newObj = new Deepcopy (); //newobj.a = new A (); //newobj.a.message = this.a.message; //newobj.i = this.i; //return NEWOBJ; //implementing Deep Replication-Mode 2: Serialization/deserializationBinaryFormatter BF =NewBinaryFormatter (); MemoryStream Ms=NewMemoryStream (); Bf. Serialize (MS, This); Ms. Position=0; returnBF.        Deserialize (MS);    }        ......    } [Serializable] Public classA { Public stringMessage ="I am the original a"; }
View Code

PS: generally inheritable types should avoid implementing the ICloneable interface , because doing so would force all subtypes to implement the ICloneable interface, otherwise the deep copy of the type would not overwrite the new members of the subclass.

. NET Foundation Supplements (1) Type syntax basics and memory Management Fundamentals 1

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.