C# 為強型別、大小寫敏感語言。掌握 var 型別推論、內建型別系統、運算子優先序與安全型別轉換模式,撰寫高效能、易維護的 Razor 程式碼。
// Using the var keyword:
var greeting = "Welcome to W3CSchool.cc";
var counter = 103;
var today = DateTime.Today;
var 由編譯器根據指派值推斷型別,**編譯時期已確定型別**,非動態型別。僅限區域變數使用。
// Using data types:
string greeting = "Welcome to W3CSchool.cc";
int counter = 103;
DateTime today = DateTime.Today;
| C# 關鍵字 | .NET 型別 | 描述 | 範圍/範例 |
|---|---|---|---|
| int | System.Int32 | 32 位元有號整數 | -2,147,483,648 ~ 2,147,483,647 |
| float | System.Single | 32 位元單精度浮點數 | ±1.5E-45 ~ ±3.4E38, 7 位數字精度 |
| double | System.Double | 64 位元雙精度浮點數 | ±5.0E-324 ~ ±1.7E308, 15-16 位精度 |
| decimal | System.Decimal | 128 位元高精度十進位 (財務首選) | ±1.0E-28 ~ ±7.9E28, 28-29 位精度 |
| bool | System.Boolean | 邏輯真偽 | true, false |
| string | System.String | Unicode 字串 (不可變) | "Hello", @"C:\Path" |
| char | System.Char | 單一 Unicode 字元 | 'A', '\n', '\u0041' |
| object | System.Object | 所有型別基底 | 任意值 |
| dynamic | System.Object (DLR) | 動態繫結 (執行時期解析) | 延遲型別檢查 |
其他整數型別:byte (0-255)、short (Int16)、long (Int64)、uint/ulong (無號)。
| 優先序 | 分類 | 運算子 | 說明 |
|---|---|---|---|
| 1 (最高) | 後綴 | x++, x-- | 後置遞增/遞減 |
| 一元 | +x, -x, !x, ~x, ++x, --x | 正負號、邏輯非、位元補數、前置遞增減 | |
| 型別轉換 | (T)x | 強制型別轉換 | |
| 2 | 乘法性 | *, /, % | 乘、除、取餘 |
| 3 | 加法性 | +, - | 加、減、字串串接 (+) |
| 4 | 位移 | <<, >> | 左移、右移 |
| 5 | 關係 | <, >, <=, >=, is, as | 比較、型別測試 |
| 6 | 等值 | ==, != | 相等、不等 (值型別比值、參考型別比參考) |
| 7 | 位元 AND | & | 位元與 |
| 8 | 位元 XOR | ^ | 位元異或 |
| 9 | 位元 OR | | | 位元或 |
| 10 | 條件 AND | && | 短路邏輯與 |
| 11 | 條件 OR | || | 短路邏輯或 |
| 12 | Null 條件 | ?? | Null 聯合運算子 |
| 13 | 條件 | ?: | 三元運算子 |
| 14 | 指派 | =, +=, -=, *=, /=, %=, ??= | 指派與複合指派 |
| 15 (最低) | Lambda | => | Lambda 運算子 |
使用者輸入 (Request、QueryString、Form) 均為字串,運算前必須驗證並轉換:
| 方法 | 功能 | 回傳 | 範例 |
|---|---|---|---|
| AsInt() / IsInt() | 轉換/檢查整數 | int / bool | if (myString.IsInt()) { myInt = myString.AsInt(); } |
| AsFloat() / IsFloat() | 轉換/檢查浮點數 | float / bool | if (myString.IsFloat()) { myFloat = myString.AsFloat(); } |
| AsDecimal() / IsDecimal() | 轉換/檢查十進位 | decimal / bool | if (myString.IsDecimal()) { myDec = myString.AsDecimal(); } |
| AsDateTime() / IsDateTime() | 轉換/檢查日期 | DateTime / bool | myDate = "10/10/2024".AsDateTime(); |
| AsBool() / IsBool() | 轉換/檢查布林 | bool / bool | myBool = "True".AsBool(); |
| ToString() | 任意型別轉字串 | string | myString = 1234.ToString(); |
進階模式: int.TryParse、DateTime.TryParseExact 提供更精細的文化特性控制與錯誤處理。生產環境建議使用 Data Annotations 驗證屬性 ([Required], [Range], [RegularExpression]) 於模型層級統一驗證。