获取可空类型的值
鉴于以下可空的 int
int? i = 10;
如果需要默认值,你可以使用空合并运算符 GetValueOrDefault
方法分配一个,或者在赋值之前检查是否为 nullable int HasValue
。
int j = i ?? 0;
int j = i.GetValueOrDefault(0);
int j = i.HasValue ? i.Value : 0;
以下用法始终不安全。如果 i
在运行时为 null,则会抛出 System.InvalidOperationException
。在设计时,如果未设置值,则会出现 Use of unassigned local variable 'i'
错误。
int j = i.Value;