※以下內容皆是新手撰寫,內容可能不完全正確
怎麼覺得好像寫了20天的英文教學文…?學程式語言跟學英文日文什麼的很像,幾天不用就會忘記(也可能是我記憶力比較短暫吧),所以盡量自己亂寫一堆(誤)
今天的主題: 結構(structures) 是C#裡面一種值型式的資料類別(忘記資料類別是做什麼的可以回去看data types),用處是讓一個變數中有其資料類型的相關資訊,以 struct關鍵字(struct keyword) 創造結構;結構裡面變數的資料類型是自己定義的,但就像其它C#裡的東西,這樣講難免抽象了點,所以會用例子做更好的解釋。
C#結構的定義和用處
結構敘述的作用是定義一個全新的資料類型,先定義某個結構才能使用。假設我今天要定義一個可以分類BL文的結構(變數名稱很重要),並且分類的依據有文名(name)、作者(author)、風格(genre)、章回數(number of chapters)和字數(word count),然後有兩篇文:
using System;
namespace CubeApplication
{
struct BLNovels
{
public string name;
public string author;
public string genre;
public int numberOfChapters;
public int wordCount;
};
class Stuff
{
static void Main(string[] args)
{
BLNovels novelX;
BLNovels novelY;
novelX.name = "Hiraeth";
novelX.author = "haruday";
novelX.genre = "angst";
novelX.numberOfChapters = 5;
novelX.wordCount = 100605;
novelY.name = "Farfalle";
novelY.author = "sw3etsociopath";
novelY.genre = "comedy";
novelY.numberOfChapters = 1;
novelY.wordCount = 26256;
Console.WriteLine("NovelX name: {0}", novelX.name);
Console.WriteLine("NovelX author: {0}", novelX.author);
Console.WriteLine("NovelX genre: {0}", novelX.genre);
Console.WriteLine("NovelX chapters: {0}", novelX.numberOfChapters);
Console.WriteLine("Novel X word count: {0}", novelX.wordCount);
Console.WriteLine("NovelY name: {0}", novelY.name);
Console.WriteLine("NovelY author: {0}", novelY.author);
Console.WriteLine("NovelY genre: {0}", novelY.genre);
Console.WriteLine("NovelY chapters: {0}", novelY.numberOfChapters);
Console.WriteLine("NovelY word count: {0}", novelY.wordCount);
}
}
}
這串又臭又長、打很久的東東執行後是這樣:
NovelX name: Hiraeth
NovelX author: haruday
NovelX genre: angst
NovelX chapters: 5
Novel X word count: 100605
NovelY name: Farfalle
NovelY author: sw3etsociopath
NovelY genre: comedy
NovelY chapters: 1
NovelY word count: 26256
(這兩個文真的存在喔~想看的自己去看)
C#中結構的特色
類別(classes)和結構(structures)的差異:
參考資料:
(a) Tutorialspoint; C# - Structures
https://www.tutorialspoint.com/csharp/csharp_struct.htm