本帖最後由 李泳霖 於 2024-1-19 14:19 編輯
在C# 中,結構是值型別資料結構。它使得一個單一變數可以儲存各種資料類型的相關資料。struct關鍵字用於建立結構。
結構是用來代表一個記錄。假設您想追蹤圖書館中書的動態。您可能想追蹤每本書的以下屬性:
- Title
- Author
- Subject
- Book ID
定義結構
為了定義一個結構,您必須使用struct 語句。struct 語句為程式定義了一個帶有多個成員的新的資料類型。- struct Books
- {
- public string title;
- public string author;
- public string subject;
- public int book_id;
- };
複製代碼- using System;
-
- struct Books
- {
- public string title;
- public string author;
- public string subject;
- public int book_id;
- };
- public class testStructure
- {
- public static void Main(string[] args)
- {
- Books Book1; /* 宣告Book1,類型為Book */
- Books Book2; /* 宣告Book2,類型為Book */
- /* 書 1 詳述*/
- Book1.title = "C Programming";
- Book1.author = "Nuha Ali";
- Book1.subject = "C Programming Tutorial";
- Book1.book_id = 6495407;
- /* 書 2 詳述*/
- Book2.title = "Telecom Billing";
- Book2.author = "Zara Ali";
- Book2.subject = "Telecom Billing Tutorial";
- Book2.book_id = 6495700;
- /* 列印Book1 訊息*/
- Console.WriteLine( "Book 1 title : {0}", Book1.title);
- Console.WriteLine("Book 1 author : {0}", Book1.author);
- Console.WriteLine("Book 1 subject : {0}", Book1.subject);
- Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
- /* 列印Book2 訊息*/
- Console.WriteLine("Book 2 title : {0}", Book2.title);
- Console.WriteLine("Book 2 author : {0}", Book2.author);
- Console.WriteLine("Book 2 subject : {0}", Book2.subject);
- Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
- Console.ReadKey();
- }
- }
複製代碼 |