C# 中的結構類型(struct)

        有時候,類中只包含極少的數據,因爲管理堆而造成的開銷顯得極不合算。這種情況下,更好的做法是使用結構(struct)類型。由於 struct 是值類型,是在棧(stack)上存儲的,所以能有效的減少內存管理的開銷(當然前提是這個結構足夠小)。
        結構可以包含它自己的字段、方法和構造器。
        int 實際上是 Sysytem.Int32 結構類型。


        編譯器始終會生成一個默認的構造器,若自己寫默認構造器則會出錯(默認構造器始終存在)。自己只能寫非默認構造器,並且在自己寫的構造器中初始化所有字段。

    struct Time
    {
        public Time()
        { 
           // 編譯時錯誤:Structs cannot contain explicit parameterless constructors
        }
    }

    struct NewYorkTime
    {
        private int hours, minutes, seconds;

        public NewYorkTime(int hh, int mm)
        {
            hours = hh;
            minutes = mm;
        }   // 編譯時錯誤,因爲 seconds 未初始化
    }

        可以使用 ? 修飾符創建一個結構變量的可空(nullable)的版本。然後把 null 值賦給這個變量。

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

namespace structType
{
    class Program
    {
        static void Main(string[] args)
        {
            NewYorkTime? currentTime = null;    // 結構類型也是值類型,可以聲明爲可空
        }
    }

    struct NewYorkTime
    {
        private int hours, minutes, seconds;

        public NewYorkTime(int hh, int mm)
        {
            hours = hh;
            minutes = mm;
            seconds = 0;
        }
    }
}
        默認構造器不需要也不能自己定義,默認構造器會把所有的自動初始化爲 0 。

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

namespace structType
{
    class Program
    {
        static void Main(string[] args)
        {
            Time now = new Time();  // 調用默認構造器,從而自動初始化,所有字段爲 0
        }
    }

    struct Time
    {
        private int hours, minutes, seconds;
    }
}

        字段(field)值如下:


        下面這種方式,結構將不會被初始化,但是也不能訪問。

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

namespace structType
{
    class Program
    {
        static void Main(string[] args)
        {
            Time now;  // 不進行初始化,若訪問字段的值會造成編譯錯誤
        }
    }

    struct Time
    {
        private int hours, minutes, seconds;
    }
}
        字段(field)值如下

        自己定義的構造器必須在構造器內把所有的字段初始化。

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

namespace structType
{
    class Program
    {
        static void Main(string[] args)
        {
            Time now = new Time(12, 30);
        }
    }

    struct Time
    {
        private int hours, minutes, seconds;

        public Time(int hh, int mm)
        {
            hours = hh;
            minutes = mm;
            seconds = 0;
        }
    }

}
        字段(field)值如下

        結構中的字段不能在聲明的同時進行初始化。

struct Time
{
    private int hours = 0;  // 報錯 'Time.hours': cannot have 
                            // instance field initializers in structs

    private int minutes, seconds;

    public Time(int hh, int mm)
    {
        hours = hh;
        minutes = mm;
        seconds = 0;
    }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章