源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-02-15 10:30 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:浅谈C# 中的可空值类型 null
C# 不允许把 null 赋给一个值类型的数据。在 C# 中,以下语句是非法的:
[u]复制代码[/u] 代码如下:
int a = null;    // 非法 
但是,利用 C# 定义的一个修饰符,可将一个变量声明为一个可空(nullable)值类型。可空值类型在行为上与普通值类型相似,但可以将一个 null 值赋给它。如下所示:
[u]复制代码[/u] 代码如下:
int? a = null;      // 合法
当把一个变量定义为可空值类型时,该变量依然可以被赋值为 0,代码如下所示:
[u]复制代码[/u] 代码如下:
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);         }     } }
运行结果为: [img]http://files.jb51.net/file_images/article/201312/2013122154741128.gif[/img] 可空类型有如下属性:
[u]复制代码[/u] 代码如下:
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 就有了优势
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部