C#简单判空

本文通过示例详细介绍了C#中如何判断Nullable类型的变量是否为空,包括使用`== null`、`.HasValue`属性以及针对对象成员的空判断表达式`?.`。同时还涉及了类型判断和空合并操作符`??`的应用。

      Nullable<int> a =new System.Nullable<int>(10);
          
          Report.Info("传入参数类型 "+a.GetType());   //传入参数类型 System.Int32  
 
          Report.Info("传入参数 "+a);        //传入参数 10  
 
          
 1、         if(a==null){                      // int不为空           
              
                  Report.Info("int为空");         
              
          }else{
              
                  Report.Info("int不为空");
              
          }
   2、     Nullable<int> b=null;
            
            if(b.HasValue){          // int为空      
              
                  Report.Info("int不为空");
                   
              
          }else{
              
                  Report.Info("int为空");
              
          }
3、        string A = "类型";
          
         if(A.GetType()==typeof(int)){             //类型不同
              
                  Report.Info("类型相同");
                   
              
          }else{
              
                  Report.Info("类型不同");
              
          }
            
 4、        int? c=new int?(2);
        
        int? d=b??c;        //如果b为空,返回c
        int? e=a??c;         //如果a不为空,返回a
        Report.Info("d= "+d+";e= "+e);           //d= 2;e= 10

 5、    Point p = new Point(4,5);
        
        if(p.X.GetType()==typeof(int)){           //如果对象为NULL,则不进行后面的获取成员的运算,直接返回NULL
            
            Report.Info("X不为空");          //(p?.X.GetType() == typeof(int?));        //true
            
        }else{
              
                  Report.Info("X为空");
              
          }

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值