從可空存中獲取預設值
即使 .HasValue
屬性為 false,.GetValueOrDefault()
方法也會返回一個值(與引發異常的 Value 屬性不同)。
class Program
{
static void Main()
{
int? nullableExample = null;
int result = nullableExample.GetValueOrDefault();
Console.WriteLine(result); // will output the default value for int - 0
int secondResult = nullableExample.GetValueOrDefault(1);
Console.WriteLine(secondResult) // will output our specified default - 1
int thirdResult = nullableExample ?? 1;
Console.WriteLine(secondResult) // same as the GetValueOrDefault but a bit shorter
}
}
輸出:
0
1