博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#2.0中的可空类型

Posted on 2006-11-04 08:46  BertonZhong  阅读(1436)  评论(2编辑  收藏  举报

1、可空类型是 System.Nullable 结构的实例,可见是值类型。无法创建基于引用类型的可空类型。(引用类型已支持 null 值)。
2、可空类型表示:基础值类型正常范围内的值+null,Nullable<bool>Nullable<bool> 可以被赋值为 truefalsenull。
3、定义:T?System.Nullable<T>此处的 T 为值类型。
4、为可空类型赋值与为一般值类型赋值的方法相同,如 int? x = 10;
5、使用 ?? 运算符分配默认值,当前值为空的可空类型被赋值给非空类型时将应用该默认值,如 int? x = null;   int  y = x ?? -1;。如果基础类型的值为 null,请使用 System.Nullable.GetValueOrDefault 属性返回该基础 类型所赋的值或默认值,例如 int j = x.GetValueOrDefault()(为null时候返回默认值,否则返回当前值)。
6.HasValue 和 Value 只读属性测试是否为空和检索值,例如 if(x.HasValue) j = x.Value。
示例:

 1using System;
 2using System.Collections.Generic;
 3
 4class 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}
结果:
num = 1
value = 1
num = null
可为空的对象必须具有一个值。


示例:??运算符
 1using System;
 2
 3class 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

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