1、可空类型是
2、可空类型表示:基础值类型正常范围内的值+null,Nullable<bool>Nullable<bool> 可以被赋值为 true 或 false或 null。
3、定义:T?和System.Nullable<T>此处的 T 为值类型。
4、为可空类型赋值与为一般值类型赋值的方法相同,如 int? x = 10;
5、使用 ?? 运算符分配默认值,当前值为空的可空类型被赋值给非空类型时将应用该默认值,如 int? x = null; int y = x ?? -1;。如果基础类型的值为 null,请使用 int j = x.GetValueOrDefault()(为null时候返回默认值,否则返回当前值)。
6.HasValue 和 if(x.HasValue) j = x.Value。
示例:
1
using System;
2
using System.Collections.Generic;
3
4
class NullableBasics
5

{
6
static void DisplayValue(int? num)
7
{
8
if (num.HasValue == true)
9
{
10
Console.WriteLine("num = " + num);
11
}
12
else
13
{
14
Console.WriteLine("num = null");
15
}
16
17
// 如果 num.HasValue 为 false,则 num.Value 引发 InvalidOperationException
18
try
19
{
20
Console.WriteLine("value = {0}", num.Value);
21
}
22
catch (InvalidOperationException e)
23
{
24
Console.WriteLine(e.Message);
25
}
26
}
27
28
static void Main()
29
{
30
DisplayValue(1);
31
DisplayValue(null);
32
Console.Read();
33
34
}
35
}
结果:
using System;2
using System.Collections.Generic;3

4
class NullableBasics5


{6
static void DisplayValue(int? num)7

{8
if (num.HasValue == true)9

{10
Console.WriteLine("num = " + num);11
}12
else13

{14
Console.WriteLine("num = null");15
}16

17
// 如果 num.HasValue 为 false,则 num.Value 引发 InvalidOperationException18
try19

{20
Console.WriteLine("value = {0}", num.Value);21
}22
catch (InvalidOperationException e)23

{24
Console.WriteLine(e.Message);25
}26
}27

28
static void Main()29

{30
DisplayValue(1);31
DisplayValue(null);32
Console.Read();33
34
}35
}num = 1
value = 1
num = null
可为空的对象必须具有一个值。
示例:??运算符
1
using System;
2
3
class NullableOperator
4

{
5
static int? GetNullableInt()
6
{
7
return null;
8
}
9
10
static string GetStringValue()
11
{
12
return null;
13
}
14
15
static void Main()
16
{
17
// ?? 运算符示例。
18
int? x = null;
19
20
// y = x,只有当 x 为 null 时,y = -1。
21
int y = x ?? -1;
22
Console.WriteLine("y == " + y);
23
24
// 将方法的返回值赋给 i,
25
// 仅当返回值为 null 时,
26
// 将默认的 int 值赋给 i。
27
int i = GetNullableInt() ?? default(int);
28
Console.WriteLine("i == " + i);
29
30
// ?? 也适用于引用类型。
31
string s = GetStringValue();
32
// 显示 s 的内容,仅当 s 为 null 时,
33
// 显示“未指定”。
34
Console.WriteLine("s = {0}", s ?? "null");
35
Console.Read();
36
}
37
}
38
using System;2

3
class NullableOperator4


{5
static int? GetNullableInt()6

{7
return null;8
}9

10
static string GetStringValue()11

{12
return null;13
}14

15
static void Main()16

{17
// ?? 运算符示例。18
int? x = null;19

20
// y = x,只有当 x 为 null 时,y = -1。21
int y = x ?? -1;22
Console.WriteLine("y == " + y); 23

24
// 将方法的返回值赋给 i,25
// 仅当返回值为 null 时,26
// 将默认的 int 值赋给 i。27
int i = GetNullableInt() ?? default(int);28
Console.WriteLine("i == " + i); 29

30
// ?? 也适用于引用类型。31
string s = GetStringValue();32
// 显示 s 的内容,仅当 s 为 null 时,33
// 显示“未指定”。34
Console.WriteLine("s = {0}", s ?? "null");35
Console.Read();36
}37
}38

结果:
y == -1
i == 0
s = null
