VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之C# 可空值类型

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

复制代码
using System;
 
/***********************************************************************************
 * 创建人:  
 * 创建时间:
 * 功能描述:
 * =====================================================================  
 * 修改人:
 * 修改时间: 
 * 功能描述:  
 ************************************************************************************/
namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //可空值类型
            double? pi = null;
            char? letter = 'a';
            
            //判空
            if (letter.HasValue)
            {
                Console.WriteLine(letter.Value);
            }
            if (pi.HasValue)
            {
                Console.WriteLine(pi.Value);
            }
 
            //如果空,给一个值
            double pi1 = pi ?? 3.14;
 
            //空参与运算
            int? a = 10;
            int? b = null;
            a = a + b;
            if (a == null)
            {
                Console.WriteLine("a为空");
                Console.WriteLine(a>10);// false
            }
 
            //判断类型是否为可空类型
            Console.WriteLine($"int? is {(IsNullable(typeof(int?)) ? "nullable" : "non nullable")} value type");
            Console.WriteLine($"int is {(IsNullable(typeof(int)) ? "nullable" : "non-nullable")} value type");
 
            //如果type不可为空,则GetUnderlyingType方法返回空
            bool IsNullable(Type type) => Nullable.GetUnderlyingType(type) != null;
        }      
    }
}
复制代码
判断可空类型要谨慎,切勿使用GetType方法和is关键字。而应使用typeof和Nullable.GetUnderlyingType方法。如果空值类型参与运算,可能得出null,也可能是其他固定的值例如false、ture。
 
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/builtin-types/nullable-value-types#code-try-7
 
量变会引起质变。
相关教程