手机
当前位置:查字典教程网 >编程开发 >C#教程 >浅谈C# 中的可空值类型 null
浅谈C# 中的可空值类型 null
摘要:C#不允许把null赋给一个值类型的数据。在C#中,以下语句是非法的:复制代码代码如下:inta=null;//非法但是,利用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 可空类型

{

class Program

{

static void Main(string[] args)

{

int? a = null;

Console.WriteLine("a = {0}", a);

a = 0;

Console.WriteLine("a = {0}", a);

}

}

}

运行结果为:

浅谈C# 中的可空值类型 null1

可空类型有如下属性:

复制代码 代码如下:

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# 中的可空值类型 null】相关文章:

C# 遍历枚举类型的所有元素

C#中实现任意List的全组合算法代码

C#加密在实际中的应用

浅谈关于C#的垃圾回收机制

C#中Convert.ToInt32()和int.Parse()的区别介绍

C#难点逐个击破(8):可空类型System.Nullable

浅谈c# 泛型类的应用

C# 判断字符串为空的几种办法

浅析C# web访问mysql数据库-整理归纳总结

C#中timer类的用法总结

精品推荐
分类导航