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。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM