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为空");
}

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

1150





