zoukankan      html  css  js  c++  java
  • 结构(值类型)的构造器

    1. internal struct Point{  
    2.     public Int32 m_x, m_y;  
    3. }  
    4. internal sealed classs Rectangle {  
    5.     public Point m_topLeft, m_bottomRight;  
    6. }  

     

    在构造Rectangle时候,需要使用new 显式调用C#编译器自动生成的默认构造器。在为Rectangle分配内内存时,由于性能问题,不会为主动调用包含在内的每个值类型字段的构造器。值类型的字段会被初始化为0或null。

     

    1. internal struct Point  
    2. {  
    3.     public Int32 m_x, m_y;  
    4.     
    5.     public Point(int32 x, Int32 y)  
    6.     {  
    7.         m_x = x;  
    8.         m_y = y;  
    9.     }  
    10. }  
    11.     
    12. internal sealed class Rectangle  
    13. {  
    14.     public Point m_topLeft, m_bottomRight;  
    15.     public Rectangle()  
    16.     {  
    17.         m_topLeft = new Point(1, 2);  
    18.         m_bottomRight = new Point(100, 200);  
    19.     }  
    20. }

    值类型的构造器 只有显示调用才会执行;

    1. internal struct Point  
    2. {  
    3.     public Int32 m_x, m_y;  
    4.     
    5.     public Point()  
    6.     {  
    7.         m_x = m_y = 5;  
    8.     }  
    9. }  
    10.     
    11. internal sealed class Rectangle  
    12. {  
    13.     public Point m_topLeft, m_bottomRight;  
    14.     public Rectangle() {  
    15.     }  

    上述还是不会调用,Point的无参构造器,编译器不会自动生成代码调用。这里会报错 error CS0568:结构不能包含显示的无参数构造器;

     

    由于没有无参数构造器,下例也是无法执行

    1. internal struct SomeValType  
    2. {  
    3.     //不能在值类型值内敛实例字段的初始化  
    4.     private Int32 m_x = 5;  
    5. }  

        在访问值类型的任何字段之前,都需要对全部字段进行赋值。所以,值类型的任何构造器都必须初始化值类型的全部字段。

    1. internal struct SomeValType  
    2. {  
    3.     private Int32 m_x, m_y;  
    4.     //不能在值类型值内敛实例字段的初始化  
    5.    public SomeValType(Int32 x)  
    6.     {  
    7.         m_x = x;   
    8.         //m_y没有进行初始化  
    9.     }  
    10. }  

      上例由于没有给m_y赋值所以会报错。

       

    11. public SomeValType(Int32 x)  
    12. {  
    13.     //会将所有字段初始化化为0/null  
    14.     this = new SomeValType();  
    15.     
    16.     m_x = x;  
    17.     //覆盖 m_x0  
    18.     //m_y已经初始化为0  
    19. 在值类型的构造其中,this代表值类型的本身的一个实例,用new创建的值类型的一个实例可以赋给this。在new的过程中,会将所有字段重置为零。而在引用类型的构造器中,this为只读的,所以不能对它进行赋值。

  • 相关阅读:
    [转]在Ubuntu 下安装Redis 并使用init 脚本启动
    [资源]PHP使用消息队列
    [转]reids客户端 redis-cli用法
    [转]redis.conf的配置解析
    【转】微信公共号开发,提示“该公众号暂时无法提供服务,请稍后再试”,如何解决?
    [转]php 解决json_encode中文UNICODE转码问题
    [资料]Keychain 获取设备唯一
    [转]PHP 获取服务器详细信息代码
    crontab任务取消发送邮件
    [转]php返回json数据中文显示的问题
  • 原文地址:https://www.cnblogs.com/ILoveMyJob/p/10809645.html
Copyright © 2011-2022 走看看