基本介紹

C# 主要為物件導向(OOP)語言

C# 為強型別語言, 相對於Python為弱型別

強型別:需要先宣告 variable type

弱型別:不需先宣告 variable type

1
2
3
4
5
6
7
8
9
# 強型別, 需先宣告 type, 程式才能判別 varaible type 並使用
int num;
num = 10;
string str;
str = "vocabulary";

# 弱型別, 不須宣告 type, 程式會自行判斷類別並直接使用
num = 10
str = "vocabulary"

變數類別

基本資料型別 => 泛指能用言語表達, 能有實際的定值

衍生性資料性別 => 除了基本資料型別以外的通通都是衍生型

基本資料型別

e.g. int, char, float, double, boolean

衍生型資料型別

e.g. string,


基本型

int 4Byte, 作為純數值, 若有小數點, 預設無條捨去, 範圍:-21474783647~21474783647 => int8, int16, int32, int64, 默認 int 一般就是int32

int number = 2147483647;

char 字元, 表示只含一個字母

char c = 'c';

float 4Byte => 單精度浮點數, double 8Byte 倍經度浮點數

如果要在C#中使用 float 要在浮點數後方補上 f

float flo = 12.5f;

double dou = 12.5;

boolean 就是布林值, True or False

bool bol = true; // 正正得正, 正負得負


衍生型

string 字串 => 中文2Byte 英文1Byte

string str = "Hello";


邏輯/運算判斷符號

! 用於進行邏輯NOT運算, 例如 bool result = !true;

&& 用於進行邏輯AND運算, 例如 bool result = (true && false);

|| 用於進行邏輯OR運算, 例如 bool result = (true || false);

+ 用於數字相加, 例如 int result = 5 + 3; 結果 int result = 8;

- 用於數字相減, 例如 int result = 5 - 3; 結果 int result = 2;

/ 用於數字相除, 例如 int result = 7 / 2; 結果 int result = 3, 小數點自動去除;

% 用於取數字餘數, 例如 int result = 10 % 3; 結果 int result = 1;

& 用於位元與, 例如 int result = 5 & 3; 結果 int result = 1 (使用 2 進制數位邏輯);

| 用於位元或, 例如 int result = 5 | 3; 結果 int result = 7 (使用 2 進制數位邏輯);


迴圈(Loop)

常見的迴圈有三種 for, while, foreach

for => 有限次數內, 重複執行, 基本上用在確定迴圈次數的狀態

while => 在條件為 true 的情況下, 重複執行, 可能會變成 無窮迴圈

foreach => 用在遍歷(traverse)集合(set), array, list 等等中的每一個 element

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// for
// output 1~9
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}

// while
// output 1~9
int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    i++;
}

// foreach
// output 1~5
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}