C# 可空值類型

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。ui

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/builtin-types/nullable-value-types#code-try-7spa

相關文章
相關標籤/搜索