zoukankan      html  css  js  c++  java
  • 可空类型 (C# 编程指南)

    参考位置:
    http://msdn2.microsoft.com/zh-cn/library/1t3y8s4s(VS.80).aspx

    可空类型是 System.Nullable 结构的实例。
    可空类型可以表示其基础值类型正常范围内的值,再加上一个 null 值。
    例如,
    Nullable<Int32>,读作“可空的 Int32”,
    可以被赋值为 -2147483648 到 2147483647 之间的任意值,
    也可以被赋值为 null 值。

    Nullable<bool> 可以被赋值为 true 或 false,或 null。
    在处理数据库和其他包含可能未赋值的元素的数据类型时,
    将 null 赋值给数值类型或布尔型的功能特别有用。
    例如,数据库中的布尔型字段可以存储值 true 或 false,或者,该字段也可以未定义。

    class NullableExample
    {
        static void Main()
        {
            int? num = null;
            if (num.HasValue == true)
            {
                System.Console.WriteLine("num = " + num.Value);
            }
            else
            {
                System.Console.WriteLine("num = Null");
            }

            //y is set to zero
            int y = num.GetValueOrDefault();

            // num.Value throws an InvalidOperationException if num.HasValue is false
            try
            {
                y = num.Value;
            }
            catch (System.InvalidOperationException e)
            {
                System.Console.WriteLine(e.Message);
            }
        }
    }
    以上将显示输出:
    num = Null
    Nullable object must have a value.

    可空类型概述
    ------------
    可空类型具有以下特性:

    * 可空类型表示可被赋值为 null 值的值类型变量。
      无法创建基于引用类型的可空类型。(引用类型已支持 null 值。)。

    * 语法 T? 是 System.Nullable<T> 的简写,此处的 T 为值类型。这两种形式可以互换。

    * 为可空类型赋值与为一般值类型赋值的方法相同,如 int? x = 10; 或 double? d = 4.108;。

    * 如果基础类型的值为 null,请使用 System.Nullable.GetValueOrDefault 属性返回该基础类型所赋的值或默认值,  例如 int j = x.GetValueOrDefault();

    * 请使用 HasValue 和 Value 只读属性测试是否为空和检索值,
      例如 if(x.HasValue) j = x.Value;

      如果此变量包含值,则 HasValue 属性返回 True;或者,如果此变量的值为空,则返回 False。

      如果已赋值,则 Value 属性返回该值,否则将引发 System.InvalidOperationException。

      可空类型变量的默认值将 HasValue 设置为 false。未定义 Value。

    * 使用 ?? 运算符分配默认值,当前值为空的可空类型被赋值给非空类型时将应用该默认值,
      如 int? x = null; int y = x ?? -1;。

    * 不允许使用嵌套的可空类型。将不编译下面一行:Nullable<Nullable<int>> n;

     

  • 相关阅读:
    LeetCode Find Duplicate File in System
    LeetCode 681. Next Closest Time
    LeetCode 678. Valid Parenthesis String
    LeetCode 616. Add Bold Tag in String
    LeetCode 639. Decode Ways II
    LeetCode 536. Construct Binary Tree from String
    LeetCode 539. Minimum Time Difference
    LeetCode 635. Design Log Storage System
    LeetCode Split Concatenated Strings
    LeetCode 696. Count Binary Substrings
  • 原文地址:https://www.cnblogs.com/freeliver54/p/823701.html
Copyright © 2011-2022 走看看