zoukankan      html  css  js  c++  java
  • 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 = 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 就有了优势

     
  • 相关阅读:
    帆软学习之开始
    「csp模拟」模拟测试11
    「csp模拟」模拟测试4
    「csp模拟」模拟测试3
    「csp模拟」模拟测试2
    「csp模拟」模拟测试1
    layui表格中日期格式的处理,从数字变日期格式
    Layui下拉框的事件和表格的刷新
    Layui的下拉框
    Layui按钮的禁用和恢复
  • 原文地址:https://www.cnblogs.com/sosoft/p/3451885.html
Copyright © 2011-2022 走看看