可空类型和?? 运算符
class NullableExample
{
static void Main()
{
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}
此示例将显示输出:
num = Null
Nullable object must have a value.
可以为 null 的类型具有以下特性:
-
可以为 null 的类型表示可被赋值为 null 值的值类型变量。无法创建基于引用类型的可以为 null 的类型。(引用类型已支持 null 值。)
-
语法 T? 是 Nullable<(Of <(T>)>) 的简写,此处的 T 为值类型。这两种形式可以互换。
-
为可以为 null 的类型赋值的方法与为一般值类型赋值的方法相同,如 int? x = 10; 或 double? d = 4.108;。
-
如果基础类型的值为 null,请使用 Nullable<(Of <(T>)>)..::.GetValueOrDefault 方法返回该基础类型所赋的值或默认值,例如 int j = x.GetValueOrDefault();
-
请使用 HasValue 和 Value 只读属性测试是否为空和检索值,例如 if(x.HasValue) j = x.Value;
-
如果此变量包含值,则 HasValue 属性返回 True;或者,如果此变量的值为空,则返回 False。
-
如果已赋值,则 Value 属性返回该值。否则,将引发 System..::.InvalidOperationException。
-
可空类型变量的默认值将 HasValue 设置为 false。未定义 Value。
-
-
使用 ?? 运算符分配默认值,当前值为空的可以为 null 的类型被赋值给非空类型时将应用该默认值,如 int? x = null; int y = x ?? -1;。
-
不允许使用嵌套的可以为 null 的类型。将不编译下面一行:Nullable<Nullable<int>> n;
?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
static void Main()
{
// ?? operator example.
int? x = null;
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);
string s = GetStringValue();
// ?? also works with reference types.
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine(s ?? "Unspecified");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步