. NET Beauty Reading notes 1

Source: Internet
Author: User

C # Type base value types and reference types
    1. Stack is an advanced, post-out data structure in which variables are assigned to the stack for operation.
    2. A heap is an area of memory that is used to allocate space for an instance (object) of a reference type, creating an object on the heap,
      The address of the object is passed to the variable on the stack.
Value type

When declaring a variable of a value type, the variable itself contains all the fields of the value type, and the value variable is assigned to the thread stack.

    public struct ValPoint    {        public int x;        public ValPoint(int x)        {            this.x = x;        }    }    //调用    ValPoint vPoint1 = new ValPoint(10);

Value type structure diagram

    • Before a struct invokes a method on a struct, it needs to assign all its fields;
    • A struct has an implicit parameterless constructor, the constructor initializes the struct member (through new calls the constructor), the value type is given 0, and the reference type is given null;
    • struct custom constructors, each struct member must be initialized within the constructor;

      Reference type

      When declaring a reference-type variable and using the new operator to create a reference-type instance, the reference variable is assigned to the line stacks (Stack), which holds the memory address of the instance of the reference type on the heap (heap).

      public class RefPoint{    public int x;    public RefPoint(int x)    {        this.x = x;    }}//调用RefPoint rPoint1 = new RefPoint(10);

      Reference type structure diagram:

Packing and unpacking

Steps for Boxing

  1. Allocating memory to newly generated object instances in the heap (heap)
  2. Copy the stack (stack) value to the heap (Head)-born object
  3. Returns the address of the object created by the heap to the reference type variable

            int i = 1;        object boxed = i;

    Unpacking the opposite operation, so boxing and unpacking is a time-consuming operation.

    Reference types such as object judgments, etc.

    There are 3 methods for System.Object base type, and three methods are analyzed.

    //比较引用变量是否指向堆(Heap)上的同一实例对象public static bool ReferenceEquals(object objA, object objB){    return objA == objB;}//实例方法,供派生类重写(override),(派生类未重写默认用基类,但只有指向同一实例对象返回true)public virtual bool Equals(object obj){    return RuntimeHelpers.Equals(this, obj);}// 如果一个为null返回falsepublic static bool Equals(object objA, object objB){    return objA == objB || (objA != null && objB != null && objA.Equals(objB));}

    Here's some code to validate the method

    RefPoint rPoint1 = new RefPoint(1);RefPoint rPoint2 = rPoint1;result = (rPoint1 == rPoint2);//TrueConsole.WriteLine(result);result = rPoint1.Equals(rPoint2);//TrueConsole.WriteLine(result);RefPoint rPoint3 = new RefPoint(2);RefPoint rPoint4 = new RefPoint(2);result = (rPoint3 == rPoint4);//FalseConsole.WriteLine(result);result = rPoint3.Equals(rPoint4);//FalseConsole.WriteLine(result);
    Value type of the award, etc.

    The

    value type implicitly inherits Valuetype,valuetype inherits object and override the Equals method. The Equals method after override mainly compares the steps

        public override bool Equals (object obj) {//1. Whether the passed-in object is null if (obj = = null) {retur        n false; }//2. Type RuntimeType RuntimeType = (RuntimeType) base.        GetType (); RuntimeType left = (runtimetype) obj.        GetType ();        if (left! = RuntimeType) {return false; }//3. For the system base type, you can directly compare if (Valuetype.cancomparebits (this)) {return Valuetype.fastequalscheck (        this, obj); }//4. Use reflection to traverse a value type member (there is recursion) fieldinfo[] fields = Runtimetype.getfields (BindingFlags.Instance | BindingFlags.Public |        BindingFlags.NonPublic); for (int i = 0; i < fields. Length; i++) {Object obj2 = ((rtfieldinfo) fields[i]).            Unsafegetvalue (this); Object obj3 = ((rtfieldinfo) fields[i]).            Unsafegetvalue (obj);                if (obj2 = = null) {if (obj3! = null) {return false;     }            }       else if (!obj2.            Equals (OBJ3)) {return false;    }} return true; }

    Caller ID Code Verification

    ValPoint vPoint1 = new ValPoint(1);ValPoint vPoint2 = new ValPoint(1);result = vPoint2.Equals(vPoint2);Console.WriteLine(result);//True
    Analysis of complex sentences, etc.
  4. Packing

    ValPoint vPoint1 = new ValPoint(1);result = object.ReferenceEquals(vPoint1, vPoint1);Console.WriteLine(result);//False
    Small partners confused, why is clearly the same variable put back false. In fact, the parameter type of the ReferenceEquals function is type object,
    Implicit boxing occurs here, so the heap (heap) is a two different instance.
  5. Override Equals method

    ValPoint vPoint1 = new ValPoint(1);ValPoint vPoint2 = new ValPoint(1);object obj1 = vPoint1;object obj2 = vPoint2;result = (obj1.Equals(obj2));//True
    Return true, I do not know if you are correct. Because struct implicitly inherits ValueType, so obj1. Equals (OBJ2) actually calls the Equals method of the ValueType type override.
  6. Value types contain reference type members

    public struct ValLine{    public RefPoint rPoint;    public ValPoint vPoint;    public ValLine(RefPoint rPoint,ValPoint vPoint)    {        this.rPoint = rPoint;        this.vPoint = vPoint;    }}//调用    RefPoint rPoint = new RefPoint(1);    ValPoint vPoint1 = new ValPoint(1);    ValPoint vPoint2 = new ValPoint(1);    ValLine vLine1 = new ValLine(rPoint, vPoint1);    ValLine vLine2 = new ValLine(rPoint, vPoint2);    result = vLine1.Equals(vLine2);//True

    What do you think put back true,valuetype write equals. Using reflection to traverse the Valline type member, the Refpoint reference type does not return false because the same instance on the heap (heap) does not return false, and the method that continues to traverse equals under the Valpoint type is not returned.

    Object Copy Shallow copy

    Refers to the distinction of a member of an object. When a member of an object is a value type, it copies itself; The member of the object is a reference type when only the reference is copied, not a new instance is created on the heap (heap).
    How a reference type needs to implement a shallow copy requires implementation of the ICloneable interface. Need to add Class

    public class RefLine:ICloneable{    public RefPoint rPoint;    public ValPoint vPoint;    public RefLine(RefPoint rPoint, ValPoint vPoint)    {        this.rPoint = rPoint;        this.vPoint = vPoint;    }    public object Clone()    {        return MemberwiseClone();    }}//调用验证值类型    ValPoint vPoint = new ValPoint(1);    RefPoint rPoint = new RefPoint(2);    ValLine vLine1 = new ValLine(rPoint, vPoint);    ValLine vLine2 = vLine1;    vLine2.vPoint.x = 3;    vLine2.rPoint.x = 4;    Console.WriteLine(vLine1.vPoint.x);//1    Console.WriteLine(vLine1.rPoint.x);//4//调用验证引用类型    ValPoint vPoint = new ValPoint(1);    RefPoint rPoint = new RefPoint(2);    RefLine rLine1 = new RefLine(rPoint, vPoint);    RefLine rLine2 = rLine1.Clone() as RefLine;    rLine2.vPoint.x = 3;    rLine2.rPoint.x = 4;    Console.WriteLine(rLine1.vPoint.x);//1    Console.WriteLine(rLine1.rPoint.x);//4

    Value types Shallow copy structure diagram:

Reference type shallow copy structure diagram:

Deep copy

A

Deep copy is also a copy of the object to which the reference member points. A reference member may point to a reference, so a deep copy is very complex and a simple workaround is serialized.

    [Serializable] public struct Valpoint {public int x;        public valpoint (int x) {this.x = x;        }} [Serializable] public class Refpoint {public int x;        public refpoint (int x) {this.x = x;        }} [Serializable] public class Refline {public Refpoint rpoint;        Public Valpoint Vpoint;            Public Refline (Refpoint rpoint, Valpoint vpoint) {this.rpoint = Rpoint;        This.vpoint = Vpoint;            } public Object Clone () {BinaryFormatter BF = new BinaryFormatter ();            MemoryStream ms = new MemoryStream (); Bf.            Serialize (MS, this); Note Set the start position of the stream in Ms.            Position = 0; Return (BF.        Deserialize (ms));    }}//call Valpoint Vpoint = new Valpoint (1);    Refpoint rpoint = new Refpoint (2);    Refline rLine1 = new Refline (Rpoint, vpoint); Refline rLine2 = Rline1.clone () as RefliNe    Rline2.vpoint.x = 3;    Rline2.rpoint.x = 4; Console.WriteLine (rline1.vpoint.x);//1 Console.WriteLine (rline1.rpoint.x);//2
Immutable types

A string type is a special type of reference, called an immutable type. So what do we need to do to create an immutable type ourselves?
Two properties required for an immutable type

  • Object atomicity: The state of an object is a whole, and if one field changes, the other fields are changed accordingly.
  • The constant nature of an object: Once the state of an object is determined, it cannot be changed again.

     public struct address{//object constant type private readonly string province; Private readonly string City; Private readonly string zip; For general reference types (constants need to be modified) private readonly string[] phones; To guarantee the atomicity of an object, the constructor succeeds or fails every time the public Address (String province, String city, String zip, string[] phones) {This.ci ty = city; this.province = Province; This.zip = Zip; This.phones = phones; Checkzip (Zip); } public string Province {get {return province;}} public string City {get {return city;}} public string Zip {get {return Zip;}} Prevents modifying member variables within a reference type private string[] Phones {get {string[] Rtn = new String[phones. Length]; Phones. CopyTo (RTN, 0); return RTN; }} private void Checkzip (string value) {string pattern = @ "\d{6}"; if (! Regex.IsMatch (value, pattern)) {throw new Exception ("Zip is invalid!"); } }}

    The beauty of. Net Zhang Ziyang

. NET Beauty Reading notes 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.