当前位置:网站首页>深入理解C# 可空类型
深入理解C# 可空类型
2022-07-29 10:56:00 【weixin_44326283】
值类型变量为什么不能为空
null在内存中是以全0存在的。值类型变量的值存储在内存中就会自动在值后面添加一个全0的值用来限制值类型变量的值范围。引用类型没有这种机制,所以引用类型可以为空,而值类型不能为空。但因为数据库中的所有类型都能为空,所以希望值类型能为空。
C#1中给值类型为空的方式
名称 | 具体操作 |
魔值 | 将具体的一个数作为空值,例如DateTime中的空值传给数据库中为0001-01-01 00:00:00 |
引用类型包装 | 进行装箱和拆箱 |
额外的不二标志 | 将值类型用另一个值类型进行空值判断 |
Nullable<T>
属性1:HasValue,判断是否有值
属性2:Value,真实的值
方法GetValueOrDefault,如果有真实的值就返回那个值,如果没有就返回默认值,方法的形参中可以添加值类型参数作为默认值。
C#中空值与空值或没有值相等,空值小于其他任何值。
C#2为可空类型提供的语法糖
在声明值类型时,使用?修饰符,例如:int? i; 这种方法实际是对值类型进行装箱的简化操作。
可空类型接受任何类型的隐式转换,但是可空类型必须显示转换为其他类型,并且转换为掐他类型时不能为空。
C#中的??操作符可以看作是判断空值的三元运算的简化版本。例如:
int? a = 4;
int b = 3;
int c = a ?? b;
a为空时,c等于b;a不为空时,c等于a。其中a必须为可空类型否则就没有什么意义,如果c为值类型,那么a必须有值或者b必须为值类型。
??操作符还可以连用,例如:
int? a = 3;
int? b = 2;
int c = 3;
int d = a ?? b ?? c;
整个语句的执行机制与上面的相同,不过是先从右边开始的,即先开始判断b和c(ps:刚开始接触觉得特别反人类,因为其他操作符都是从左边先开始的)。
总结:要给值类型变量赋空值,就在声明时的修饰符后添加?,使用??可以起到一个排序的效果。
边栏推荐
- R language Monte Carlo method and average method are used to calculate the definite integral. Considering the random point casting method, the confidence is 0.05, and the requirement is ϵ= 0.01, numbe
- 聊聊性能测试环境搭建
- LeetCode_ 1049_ Weight of the last stone II
- Sunwenlong, Secretary General of the open atom open source foundation, worked together to expand open source
- Ggdag draw DAG and cause and effect diagram
- 开源峰会抢先看 | 7月29日分论坛&活动议程速览
- Conference OA project - my approval
- Hutool日期时间
- R 语言 二分法与 牛顿迭代法计算中方程的根
- R 语言 Monte Carlo方法 和平均值法 计算定积分, 考虑随机投点法,计算在置信度0.05, 要求为ϵ=0.01 , 所需要的试验次数
猜你喜欢
如何在匹配行之前使用 grep 显示文件名和行号
报表控件FastReport与StimulSoft功能对比
QWidget、QDialog、QMainWindow 的异同点
How to realize the function of adding watermark
Review of the 16th issue of HMS core discovery | play with the new "sound" state of AI with tiger pier
Site data collection -scrapy usage notes
PyQt5快速开发与实战 6.6 QFormLayout(表单布局) && 6.7 嵌套布局 && 6.8 QSplitter
PHP basics uses arrays to save data
QT工程基本构建
Conference OA project - my approval
随机推荐
Ggdag draw DAG and cause and effect diagram
leetcode-位运算
DoD 和 DoR,消减「认知偏差」的两大神器
How to synchronize when the primary and sub warehouses are modified?
Function comparison between report control FastReport and stimulus soft
JVM知识点详细整理(长文警告)
VMware: use commands to update or upgrade VMware esxi hosts
Alibaba architects spent a year sorting out the "Lucene advanced document", and you are also a big factory employee!
通过tidymodels使用XGBOOST
一文搞懂什么是二叉树(二叉树的种类、遍历方式、定义)
Talk about the establishment of performance testing environment
LeetCode_ 1049_ Weight of the last stone II
GBase8s Informix Dodker 高可用集群自恢复集群启动命令oninitdb的设计与实现
重磅 | 2022 开放原子全球开源峰会在北京开幕
小笑授权系统V5.0开心版
Software testing dry goods
Basic construction of QT project
一键搭建博客:如何使用WordPress插件搭建专属博客
Open source, compliance escort! 2022 open atom global open source summit open source compliance sub forum is about to open
Learning R language these ebooks are enough!