C# 可空类型
讲解 C# 可空值类型 T? 与 Nullable<T> 的内存模型、单问号 ? 与双问号 ?? 空合并运算符、HasValue/Value/GetValueOrDefault 成员契约、数据库与配置实战,以及 C# 8.0+ 可空引用类型与 ??= 演进,并在本地 csc4 实测验证。
学完这一章,你能够
- 讲解 C# 可空值类型 T? 与 Nullable<T> 的内存模型、单问号 ? 与双问号 ?? 空合并运算符、HasValue/Value/GetValueOrDefault 成员契约、数据库与配置实战,以及 C# 8.0+ 可空引用类型与 ??= 演进,并在本地 csc4 实测验证。
可空值类型概念与 Nullable<T> 内存结构
在 C# 中,`int`、`float`、`bool`、`DateTime` 等值类型默认总是持有确定数值,不能直接赋值为 `null`(例如 `int a = null;` 会直接触发编译错误)。为了在数据库可空列、外部接口缺失字段等场景中准确表达“无值”状态,C# 从 2.0 起提供可空值类型(Nullable Value Types):在值类型名后附加 `?` 即可声明(如 `int? a = null; int? b = 42;`)。`int?` 本质上是泛型结构体 `System.Nullable<int>` 的编译期语法糖,二者在运行时类型完全一致;其内部同时封装了一个布尔标记 `HasValue` 与基础值槽 `Value`,当 `HasValue` 为 `true` 时读取 `Value` 返回实际数值,为 `false` 时访问 `Value` 将抛出 `InvalidOperationException`。
单问号 ?、双问号 ?? 与可空类型声明赋值
与可空值类型配套使用的 `?` 与 `??` 职责截然不同:单问号 `?` 是类型修饰符,用于把值类型扩展为可容纳 `null` 的可空类型(例如普通字段 `int i` 默认值为 `0` 且不可为 `null`,而 `int? ii` 默认值为 `null`);双问号 `??` 则是空合并运算符,用于在左侧表达式为 `null` 时返回右侧兜底默认值。
可空类型的通用声明语法为 `<data_type>? <variable_name> = null;`(例如 `int? age = null;`、`double? temperature = 36.6;`、`bool? isActive = new bool?();`、`DateTime? birthday = null;`)。`Nullable<T>` 可完整覆盖基础值类型的合法取值范围并额外增加一个 `null` 状态(如 `Nullable<int>` 涵盖 `-2,147,483,648` 至 `2,147,483,647` 及 `null`)。当对值为 `null` 的可空变量直接做字符串格式化输出时,结果为不含字符的空串。本站实测确认 `typeof(int?) == typeof(Nullable<int>)`,且 `num1..num4` 与 `boolVal` 格式化及 `??` 回退结果与预期完全一致。
Null 合并运算符 ?? 与常用成员方法
空合并运算符 `<表达式1> ?? <表达式2>` 适用于可空值类型与引用类型:当左侧 `<表达式1>` 不为 `null` 时直接返回其值,否则求值并返回右侧 `<表达式2>`;还可串联多个备选值(如 `a ?? b ?? c ?? 0`)依次回退直至命中首个非空值。自 C# 8.0 起新增空合并赋值运算符 `??=`(如 `x ??= 10;`),仅在左侧变量当前为 `null` 时才执行右侧赋值。本站 `csc4` 实测 `null ?? 5.34` 得 `5.34`、`3.14157 ?? 5.34` 得 `3.14157`,多级链式 `a ?? b ?? c ?? 0` 得 `42`。
`Nullable<T>` 提供了四个核心成员:`HasValue` 返回布尔值指示是否存在有效数据;`Value` 返回底层值但在 `null` 状态下会抛出 `InvalidOperationException`;`GetValueOrDefault()` 在 `null` 时安全返回基础类型默认值(如 `0`);`GetValueOrDefault(T defaultValue)` 在 `null` 时返回调用方指定的默认值(语义上与 `num ?? defaultValue` 等价)。本站实测对 `null` 可空整数读取 `.Value` 确实捕获 `InvalidOperationException`,而 `GetValueOrDefault()`、`GetValueOrDefault(99)` 与 `?? 99` 分别安全返回 `0`、`99`、`99`。
典型应用场景与 C# 8.0 可空引用类型演进
在工程实践中,可空值类型广泛用于两类高频场景:一是数据库可空字段映射(如用户表的 `年龄` 列可能存 `NULL`,查出后以 `int?` 接收,再通过 `HasValue` 或 `??` 安全格式化显示);二是可选配置项读取(如读取 `timeout` 配置缺失时通过 `timeout ?? 30` 回退至 30 秒默认值)。针对嵌套引用对象,C# 6.0 引入了空条件运算符 `?.`(如 `user?.Address?.City?.Name`),任一环节为 `null` 时即短路返回 `null` 而避免抛出 `NullReferenceException`(C# 5.0 中则使用显式 `!= null` 判空)。
需要注意区分 C# 8.0 新增的“可空引用类型(Nullable Reference Types,如 `string?`)”与本文核心的可空值类型(`int?`):前者作用于 `string`、`class`、数组等引用类型,需在项目配置启用 `<Nullable>enable</Nullable>`,本质上是编译期静态流分析工具,不改变运行时类型布局,只在可能解引用 `null` 处发出编译器警告;后者则是语言自 C# 2.0 起内置的 `Nullable<T>` 运行时结构体包装机制(始终可用,无需额外开关)。
单问号 ? 与双问号 ?? 运算符对比表
| 运算符 | 名称 | 核心用途 | 典型示例 |
|---|---|---|---|
| ? | 可空类型修饰符 | 将值类型包装为 Nullable<T>,使其支持 null 状态 | int? i = 3; 等价于 Nullable<int> i = new Nullable<int>(3); |
| ?? | 空合并运算符(Null-Coalescing) | 左侧为 null 时提供右侧兜底默认值 | int result = i ?? 0; |
Nullable<T> 常用属性、方法与运算符对照表
| 成员 / 运算符 | 作用与边界说明 | 使用示例 |
|---|---|---|
| .HasValue | 返回 bool,判断当前可空实例是否包含有效值 | if (num.HasValue) { ... } |
| .Value | 提取内部值;若 HasValue 为 false 则抛出 InvalidOperationException | int x = num.Value; |
| .GetValueOrDefault() | 安全取值;为 null 时返回基础值类型的默认值(如 int 返回 0) | num.GetValueOrDefault() |
| .GetValueOrDefault(T) | 安全取值;为 null 时返回传入的自定义默认值 | num.GetValueOrDefault(100) |
| ?? | 空合并运算符,左侧为 null 时返回右侧表达式(支持链式回退) | int result = num ?? 100; |
数据库可空字段映射示例表
| 用户ID | 年龄(可空列) | 是否激活 |
|---|---|---|
| 1 | 28 | true |
| 2 | null | false |
可空类型核心操作速查表
| 功能 | 示例表达式 | 行为与版本说明 |
|---|---|---|
| 定义可空类型 | int? x = null; | Nullable<int> 的简写语法糖 |
| 判断是否有值 | x.HasValue | 有值返回 true,为 null 返回 false |
| 获取值(不安全) | x.Value | 有值返回实际值,为 null 时抛出 InvalidOperationException |
| 获取默认值 | x ?? 0 | 为 null 时返回右侧兜底值 |
| 获取指定默认值 | x.GetValueOrDefault(10) | 为 null 时安全返回指定值 10 |
| 空合并赋值 | x ??= 10 | 仅当 x 为 null 时执行赋值(C# 8.0+ 特性) |
| 安全导航访问 | user?.Name | 左侧对象为 null 时短路返回 null(C# 6.0+ 特性) |
可空值类型与 C# 8.0 可空引用类型对比表
| 对比维度 | 可空值类型(int?) | 可空引用类型(string?,C# 8.0+) |
|---|---|---|
| 示例 | int?、double?、DateTime? | string?、User? |
| 作用对象 | 值类型(int、bool、struct 等) | 引用类型(string、class、数组等) |
| 实现方式 | 运行时由 System.Nullable<T> 泛型结构体包装实现 | 编译期静态空值流分析,不改变运行时对象布局 |
| 默认状态 | 自 C# 2.0 起语言内置支持,无需项目开关(注:来源误标为 1.0,实际随 2.0 泛型引入) | 需在 .csproj 启用 <Nullable>enable</Nullable> 或使用 #nullable enable |
| null 检查 | 通过 .HasValue 或 != null 在运行期判空 | 编译器对潜在 NullReferenceException 发出静态警告 |
在本地 csc4 实测 Nullable<T> 等价性、?? 链式兜底、.Value 异常与数据库/配置场景
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace CSharpNullableLab
{
internal class UserProfile
{
public int Id;
public int? Age;
public bool IsActive;
}
internal class Program
{
private static int? GetUserAgeFromDb(List<UserProfile> rows, int userId)
{
foreach (UserProfile row in rows)
{
if (row.Id == userId)
{
return row.Age;
}
}
return null;
}
private static int? GetConfigValue(Dictionary<string, int> cfg, string key)
{
int val;
if (cfg.TryGetValue(key, out val))
{
return val;
}
return null;
}
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
private static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: Declaration, syntactic sugar equivalence & default values
int? num1 = null;
int? num2 = 45;
Nullable<int> fullForm = new Nullable<int>(45);
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolVal = new bool?();
bool sameType = typeof(int?) == typeof(Nullable<int>);
string actual1 = string.Format(
CultureInfo.InvariantCulture,
"sameType={0},eq={1},n1={2},n2={3},n3={4},n4={5},boolEmpty={6}",
sameType,
num2.Equals(fullForm),
num1 ?? 0,
num2 ?? 0,
num3 ?? 0.0,
num4 ?? 0.0,
string.Format("{0}", boolVal) == ""
);
cases.Add(CaseJson(
"nullable_declaration_and_equivalence",
"验证 T? 与 Nullable<T> 类型等价、可空值类型默认值及格式化空串输出",
"sameType=True,eq=True,n1=0,n2=45,n3=0,n4=3.14157,boolEmpty=True",
actual1
));
// Case 2: Null-coalescing operator ?? and chaining
double? d1 = null;
double? d2 = 3.14157;
double r1 = d1 ?? 5.34;
double r2 = d2 ?? 5.34;
int? a = null;
int? b = null;
int? c = 42;
int chained = a ?? b ?? c ?? 0;
string actual2 = string.Format(
CultureInfo.InvariantCulture,
"r1={0},r2={1},chained={2}",
r1, r2, chained
);
cases.Add(CaseJson(
"null_coalescing_operator",
"验证 ?? 空合并运算符兜底默认值与多级链式回退求值",
"r1=5.34,r2=3.14157,chained=42",
actual2
));
// Case 3: HasValue, Value exception, GetValueOrDefault
int? emptyNum = null;
int? filledNum = 42;
string valueErr = "none";
try
{
int unused = emptyNum.Value;
valueErr = unused.ToString();
}
catch (InvalidOperationException)
{
valueErr = "InvalidOperationException";
}
string actual3 = string.Format(
"emptyHas={0},filledHas={1},filledVal={2},def0={3},def99={4},coal99={5},err={6}",
emptyNum.HasValue,
filledNum.HasValue,
filledNum.Value,
emptyNum.GetValueOrDefault(),
emptyNum.GetValueOrDefault(99),
emptyNum ?? 99,
valueErr
);
cases.Add(CaseJson(
"nullable_members_and_exception",
"验证 HasValue、GetValueOrDefault 重载以及对 null 可空类型读取 Value 抛出 InvalidOperationException",
"emptyHas=False,filledHas=True,filledVal=42,def0=0,def99=99,coal99=99,err=InvalidOperationException",
actual3
));
// Case 4: Practical scenarios (DB nullable mapping & optional config)
List<UserProfile> users = new List<UserProfile>
{
new UserProfile { Id = 1, Age = 28, IsActive = true },
new UserProfile { Id = 2, Age = null, IsActive = false }
};
int? age1 = GetUserAgeFromDb(users, 1);
int? age2 = GetUserAgeFromDb(users, 2);
string display1 = age1.HasValue ? string.Format("用户年龄:{0}", age1.Value) : "年龄未知";
string display2 = age2.HasValue ? string.Format("用户年龄:{0}", age2.Value) : "年龄未知";
Dictionary<string, int> cfg = new Dictionary<string, int>();
int actualTimeout = GetConfigValue(cfg, "timeout") ?? 30;
cfg["timeout"] = 60;
int customTimeout = GetConfigValue(cfg, "timeout") ?? 30;
string actual4 = string.Format(
"u1={0},u2={1},tDef={2},tCfg={3}",
display1, display2, actualTimeout, customTimeout
);
cases.Add(CaseJson(
"nullable_db_and_config_scenarios",
"验证数据库可空列映射与缺失配置项兜底默认值的工程用法",
"u1=用户年龄:28,u2=年龄未知,tDef=30,tCfg=60",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":{0},\"cases\":[{1}]}}",
Esc("CLR " + Environment.Version.ToString()),
string.Join(",", cases.ToArray())
));
}
}
}
- 确认 int? 与 Nullable<int> 类型一致、?? 单级与链式回退、空可空类型读取 .Value 触发 InvalidOperationException 以及数据库年龄/配置超时回退四组实验全部通过。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
当前源码 SHA256:241148bda15cdc29ee10432362cbb2e2073369f5fd262b3e5afd1f7f8e1c2dda
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
ZIP SHA256:bbd211c2aea1c750b2fe35f6cda41cfe5e2e7f8388dd6ac7e45788f20acd45e8
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 C# 中,`int?` 与 C# 8.0 引入的 `string?` 在运行时机制上有什么本质区别?
展开参考解答
`int?` 是运行时真实存在的 `System.Nullable<int>` 泛型结构体(包含 `HasValue` 标志位和 `Value` 载荷),而 `string?` 在运行时仍是普通 `System.String` 引用,仅通过元数据标注供 C# 8.0+ 编译器执行静态空值安全警告分析。