C#中的可空值类型

C# 不允许把 null 赋给一个值类型的数据。在 C# 中,以下语句是非法的:

int a = null;    // 非法

但是,利用 C# 定义的一个修饰符,可将一个变量声明为一个可空(nullable)值类型。可空值类型在行为上与普通值类型相似,但可以将一个 null 值赋给它。如下所示:

int? a = null;      // 合法

当把一个变量定义为可空值类型时,该变量依然可以被赋值为 0,代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace keleyi.com
{
class Program
{
static void Main(string[] args)
{
int? a = null; Console.WriteLine("a = {0}", a);
a = ;
Console.WriteLine("a = {0}", a);
}
}
}

可空类型有如下属性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int? i = null;
if (!i.HasValue) // 若 i 包含一个真正的值,则 i.HasValue 为true
{
i = 99;
}
Console.WriteLine(i.Value); // i 的值
}
}
}

// i.HasValue 比 i != null 走了不少冤枉路,i.Value 也比 i 更麻烦
// 但是当使用更加复杂的值类型(struct)来声明可空类型时, .HasValue 和 .Value 就有了优势

 
上一篇:C语言——strlen()和sizeof的区别


下一篇:Xshell5下利用sftp上传下载传输文件