2024-10-31 021_Ccharp變數的型別

2024-10-30 020_SOLID 原則

當你在 C# 中創建變數時,可以使用多種不同的資料型別(Types)。這些型別大致可以分為值型別(Value Types)參考型別(Reference Types)。了解這些型別有助於你更有效地管理記憶體和優化程式效能。讓我們一步步來探索 C# 中可用的各種變數型別。


目錄

  1. 值型別(Value Types)
    • 整數型別
    • 浮點數型別
    • 字元型別
    • 布林型別
    • 結構型別(Structs)
    • 列舉型別(Enums)
  2. 參考型別(Reference Types)
    • 字串型別(String)
    • 陣列型別(Arrays)
    • 類別型別(Classes)
    • 委派型別(Delegates)
    • 介面型別(Interfaces)
  3. 其他型別
    • Nullable 型別
    • 動態型別(Dynamic)
  4. 自訂型別
    • 類別(Classes)
    • 結構(Structs)
    • 列舉(Enums)
  5. 型別推斷(Type Inference)
  6. 小結

1. 值型別(Value Types)

值型別直接包含其數據,而不是指向數據的參考。它們通常儲存在堆疊(Stack)中,存取速度快。

整數型別(Integer Types)

型別 範圍 大小(位元組)
int -2,147,483,648 到 2,147,483,647 4
long -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 8
short -32,768 到 32,767 2
byte 0 到 255 1
uint 0 到 4,294,967,295 4
ulong 0 到 18,446,744,073,709,551,615 8
ushort 0 到 65,535 2
sbyte -128 到 127 1

範例:

1
2
3
int age = 25;
long distance = 9876543210L;
byte level = 255;

浮點數型別(Floating-Point Types)

型別 範圍 大小(位元組)
float 約 ±1.5 × 10^−45 到 ±3.4 × 10^38 4
double 約 ±5.0 × 10^−324 到 ±1.7 × 10^308 8
decimal 約 ±1.0 × 10^−28 到 ±7.9 × 10^28 16

範例:

1
2
3
float temperature = 36.6F;
double pi = 3.141592653589793;
decimal price = 19.99M;

字元型別(Character Type)

型別 描述 大小(位元組)
char 單一 Unicode 字元 2

範例:

1
2
char grade = 'A';
char symbol = '#';

布林型別(Boolean Type)

型別 描述 大小(位元組)
bool truefalse 1

範例:

1
2
bool isCompleted = true;
bool hasAccess = false;

結構型別(Structs)

結構是值型別的自訂型別,可以包含多個不同的成員(屬性、方法等)。

範例:

1
2
3
4
5
6
7
8
9
struct Point
{
public int X;
public int Y;
}

Point p1 = new Point();
p1.X = 10;
p1.Y = 20;

列舉型別(Enums)

列舉是一種值型別,用於定義一組命名的整數常數。

範例:

1
2
3
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

Days today = Days.Monday;

2. 參考型別(Reference Types)

參考型別儲存的是對實際數據的參考(地址),而不是數據本身。它們通常儲存在堆(Heap)中,存取速度較慢。

字串型別(String)

string 是一種特殊的參考型別,用於表示文本。

範例:

1
2
string greeting = "Hello, World!";
string name = "Alice";

陣列型別(Arrays)

陣列是用來存儲相同型別元素的集合。

範例:

1
2
int[] numbers = { 1, 2, 3, 4, 5 };
string[] fruits = new string[3] { "Apple", "Banana", "Cherry" };

類別型別(Classes)

類別是 C# 中最常用的參考型別,用於創建物件。

範例:

1
2
3
4
5
6
7
8
9
class Person
{
public string Name;
public int Age;
}

Person person1 = new Person();
person1.Name = "Bob";
person1.Age = 30;

委派型別(Delegates)

委派是一種引用方法的類型。

範例:

1
2
3
4
5
6
7
8
9
delegate void GreetingDelegate(string message);

void Greet(string message)
{
Console.WriteLine(message);
}

GreetingDelegate del = Greet;
del("Hello via delegate!");

介面型別(Interfaces)

介面定義了一組方法和屬性的合約,類別可以實作這些介面。

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface IAnimal
{
void Speak();
}

class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Dog barks");
}
}

IAnimal myDog = new Dog();
myDog.Speak(); // 輸出 "Dog barks"

3. 其他型別

Nullable 型別

有些值型別(如 intdouble)不能為 null。使用 Nullable 型別可以讓這些型別接受 null 值。

語法: 在型別後加上 ?

範例:

1
2
int? nullableInt = null;
double? nullableDouble = 3.14;

動態型別(Dynamic)

dynamic 型別在編譯時不會進行型別檢查,會在運行時決定其型別。

範例:

1
2
3
4
5
dynamic dyn = "Hello";
Console.WriteLine(dyn.Length); // 輸出 5

dyn = 100;
Console.WriteLine(dyn + 200); // 輸出 300

注意: 使用 dynamic 會失去編譯時型別檢查,需謹慎使用。


4. 自訂型別

除了內建的型別外,你還可以創建自訂型別來滿足特定需求。

類別(Classes)

類別是創建物件的藍圖,可以包含屬性、方法、事件等。

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Car
{
public string Make;
public string Model;
public int Year;

public void Start()
{
Console.WriteLine("Car started.");
}
}

Car myCar = new Car();
myCar.Make = "Toyota";
myCar.Model = "Corolla";
myCar.Year = 2020;
myCar.Start(); // 輸出 "Car started."

結構(Structs)

結構是值型別的自訂型別,通常用於輕量級的資料結構。

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Rectangle
{
public int Width;
public int Height;

public int Area()
{
return Width * Height;
}
}

Rectangle rect = new Rectangle();
rect.Width = 5;
rect.Height = 10;
Console.WriteLine(rect.Area()); // 輸出 50

列舉(Enums)

如前所述,列舉用於定義一組命名的常數。

範例:

1
2
3
enum Season { Spring, Summer, Autumn, Winter };

Season currentSeason = Season.Spring;

5. 型別推斷(Type Inference)

C# 提供了 var 關鍵字,可以在宣告變數時讓編譯器自動推斷變數的型別。這只適用於在宣告時初始化變數的情況。

範例:

1
2
3
var number = 10; // 編譯器推斷為 int
var name = "Charlie"; // 編譯器推斷為 string
var list = new List<string>(); // 編譯器推斷為 List<string>

注意: 即使使用 var,變數仍然具有靜態型別,無法在後續賦值中改變型別。


6. 小結

在 C# 中創建變數時,可以使用多種資料型別,這些型別大致可分為:

  • 值型別(Value Types):如 intdoubleboolcharstructenum 等,直接包含數據,儲存在堆疊中。
  • 參考型別(Reference Types):如 stringarraysclassesdelegatesinterfaces 等,儲存對數據的引用,存儲在堆中。
  • 其他型別:如 Nullable 型別、動態型別等,提供更靈活的型別管理。
  • 自訂型別:如 classesstructsenums,根據需求創建的自定義型別。
  • 型別推斷(Type Inference):使用 var 讓編譯器自動推斷變數型別。

了解並善用這些不同的型別,能幫助你編寫更高效、可維護的 C# 程式。如果你有任何進一步的問題或需要更詳細的範例,請隨時告訴我!