C# 8中基本數據類型的可空值類型

        C# 8中基本數據類型除了 string (string是引用類型)外,int、long、float、double、decimal、char、bool (這7中都是值類型)都可以聲明爲可空值類型。且在方法中使用時,參數位置也沒有可空值類型必須在非可空值類型後面的限制,可空值類型可以定義在方法參數列表的前中後任何位置。

        struct(結構) 類型是值類型,也可以聲明爲可空值類型。

        對於 string 類型,可以用 string.Empty 輸出空值。另外,除了 string.Empty 外,string 類型也可直接賦值爲 null。如下:

string str = null;  // 合法
string str = string.Empty;  // 合法
        代碼如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 可空類型
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student();

            student1.StudentInformation(12, "boy", 18, 180, 86.0F, 
                90.0, 95.0M, 85.0F, "Steven", 'A', true, 168);

            Console.WriteLine();

            student1.StudentInformation(12, "boy", null, null, null, 
                null, null, 85.0F, "Steven", null, null, 168);

            Console.WriteLine();

            student1.StudentInformation(12, string.Empty, null, null, null,     
                null, null, 85.0F, string.Empty, null, null, 168);

                // 對於 string 類型,可以用 string.Empty 輸出空值

            Console.WriteLine();

            student1.StudentInformation(12, null, null, null, null,
                null, null, 85.0F, null, null, null, 168);

                // 把 賦值給 string 類型的 string.Empty 
                // 換成 null 後可得到同樣的輸出
        }
    }

    class Student
    {
        //public Student()
        //{
        // 默認構造器註釋掉,依然可以運行,實際上程序會自己建一個隱藏的默認構造器
        //}       
        public void StudentInformation(
            int schoolAge,
            string sex,
            int? age,
            long? height,
            float? mathScore,
            double? biologyScore,
            decimal? geographyScore,
            float artScore,
            string name,
            char? scoreGrade,
            bool? passed, 
            int ID)
        {
            Console.WriteLine("Name:            {0}", name);
            Console.WriteLine("ID:              {0}", ID);
            Console.WriteLine("Sex:             {0}", sex);
            Console.WriteLine("Age:             {0}", age);
            Console.WriteLine("SchoolAge:       {0}", schoolAge);
            Console.WriteLine("Height:          {0}", height);
            Console.WriteLine("MathScore:       {0}", mathScore);
            Console.WriteLine("ArtScore:        {0}", artScore);
            Console.WriteLine("BiologyScore:    {0}", biologyScore);
            Console.WriteLine("GeographyScore:  {0}", geographyScore);
            Console.WriteLine("ScoreGrade:      {0}", scoreGrade);
            Console.WriteLine("Passed:          {0}", passed);
        }
    }
}

        運行後結果如下所示:


發佈了51 篇原創文章 · 獲贊 17 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章