栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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);
        }
    }
}

运行结果为:

可空类型有如下属性:

复制代码 代码如下:
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 就有了优势

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/126899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号