Share via


結構 (Visual C# Express)

更新:2007 年 11 月

C# 的結構 (Struct) 和類別 (Class) 相似,但結構缺少了某些功能,例如繼承 (Inheritance)。此外,因為結構是實值型別 (Value Type),一般來說它可以比類別更快速地建立。如果您具有大量資料結構在其中建立的緊密迴圈 (Loop),就應該考慮使用結構而不是類別。結構也用來封裝資料欄位的群組,例如格線上某個點的座標,或長方形的尺寸。如需詳細資訊,請參閱類別 (Visual C# Express)

範例

這個範例程式定義 struct 以儲存地理位置。它也會覆寫 ToString() 方法,以便顯示在 WriteLine 陳述式時產生更有用的輸出。因為 struct 中沒有方法,所以將其定義為類別並沒有好處。

struct GeographicLocation
{
    private double longitude;
    private double latitude;

    public GeographicLocation(double longitude, double latitude)
    {
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public override string ToString()
    {
        return System.String.Format("Longitude: {0} degrees, Latitude: {1} degrees", longitude, latitude);
    }
}

class Program
{
    static void Main()
    {
        GeographicLocation Seattle = new GeographicLocation(123, 47);
        System.Console.WriteLine("Position: {0}", Seattle.ToString());
    }
}

輸出

此範例的輸出如下所示:

Position: Longitude: 123 degrees, Latitude: 47 degrees

請參閱

概念

C# 程式設計手冊

C# 語言入門

類別 (Visual C# Express)

參考

class

struct

類別和結構 (C# 程式設計手冊)