当前位置:网站首页>深入理解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:刚开始接触觉得特别反人类,因为其他操作符都是从左边先开始的)。
总结:要给值类型变量赋空值,就在声明时的修饰符后添加?,使用??可以起到一个排序的效果。
边栏推荐
- 美团、饿了么被杭州市监约谈要求落实食品安全管理责任 严禁恶意竞争
- 【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
- Pyqt5 rapid development and practice 6.6 qformlayout & 6.7 nested layout & 6.8 qsplitter
- Kunlunbase instruction manual (I) quick installation manual
- 【图像处理】基于中轴变换实现图像骨架提取附matlab代码
- 大伟 GBase8s游标稳定性读ESQL测试用例
- Error: Protobuf syntax version should be first thing in file
- Kunlunbase instruction manual (II) best practices for peer-to-peer deployment
- Structure the eighth operation of the combat battalion module
- Drawing box and ellipse of WPF screenshot control (IV) "imitating wechat"
猜你喜欢

Alibaba P8 broke out this interview guide for big factories. After reading it, the salary soared by 30K!

QT工程基本构建

Zhou Hongyi: 360 is the largest secure big data company in the world

2022最新 wifi大师小程序独立版3.0.8

【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码

Conference OA project - my approval

Niuke net brush questions

Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29

Kunlun storage vs PostgreSQL OLTP test

Using Riemann sum to calculate approximate integral in R language
随机推荐
重磅 | 基金会为白金、黄金、白银捐赠人授牌
R package pedquant realizes stock download and financial quantitative analysis
Spark高效数据分析02、基础知识13篇
面试中项目讲解的步骤
WPF 截图控件之绘制方框与椭圆(四) 「仿微信」
[unity, C #] character keyboard input steering and rotation
Leetcode binary tree series -- 144. Preorder traversal of binary trees
『面试知识集锦100篇』1.面试技巧篇丨HR的小心思,你真的懂吗?
使用R包PreMSIm根据基因表达量来预测微卫星不稳定
从零开始Blazor Server(3)--添加cookie授权
Software testing dry goods
8. Interleave - understand ThreadPoolExecutor thread pool from architecture design to practice
如何使用 grep 跨多行查找模式匹配
Kunlunbase support for MySQL private DML syntax
Kunlunbase instruction manual (I) quick installation manual
GBase8s核心数据备份
LeetCode_ 1049_ Weight of the last stone II
Drawing box and ellipse of WPF screenshot control (IV) "imitating wechat"
Understand what a binary tree is (types, traversal methods, definitions of binary trees)
【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码