可为NULL的值类型
1.检查是否可空#
1.1 判断该值指示 Nullable 对象是否具有基础类型的有效值 #
int? b = 10;
if (b.HasValue) { Console.WriteLine($"b is {b.Value}"); }
//若 b = null
else { Console.WriteLine("b does not have a value"); }
Console.ReadLine();
// Output:
// b is 10
1.2 将可为空的值类型的变量与 null 进行比较#
int? c = 7;
if (c != null)
{
Console.WriteLine($"c is {c.Value}");
}
else
{
Console.WriteLine("c does not have a value");
}
// Output:
// c is 7
2.可空类型转换 ??#
2.1 使用 Null合并操作符 进行类型转换#
int? a = 28;
int b = a ?? -1;
Console.WriteLine($"b is {b}"); // output: b is 28
int? c = null;
int d = c ?? -1;
Console.WriteLine($"d is {d}"); // output: d is -1
解释
??(空合并运算符): a??b 当a为null时则返回b,a不为null时则返回a本身
2.2 使用基础值类型强转#
int? n = null;
//int m1 = n; // Doesn't compile
int n2 = (int)n; // Compiles, but throws an exception if n is null
在运行时,如果可为空的值类型的值为 null,则显式强制转换将抛出 InvalidOperationException
3.空合并运算符#
3.1 以前写法#
static void Main(string[] args)
{
int? a = null;
if (a == null)
{
a = 4;
}
Console.WriteLine(a);
Console.Read();
}
// Output: a = 4
3.2 使用 ??#
static void Main(string[] args)
{
int? a = null;
a ??= 5;
Console.WriteLine(a);
Console.Read();
}
// Output: a = 5
4.微软官方文档#
作者:DotNeter-Hpf
出处:https://www.cnblogs.com/DotNeter-Hpf/p/16620723.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
客官,点个推荐再走可好
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)