在 C/C++ 中,bool 可隱含轉換為 int (false=0, true=1),if (x) 合法。C# 嚴格禁止 bool 與其他型別隱含轉換,必須顯式比較。
// ❌ C# 編譯錯誤 CS0029:無法將 int 隱含轉換為 bool
int x = 123;
if (x) { Console.WriteLine("非零"); }
// ✅ 正確:顯式比較
if (x != 0) { Console.WriteLine("非零"); }
// ✅ 正確:邏輯判斷回傳 bool
if (x > 0) { Console.WriteLine("正數"); }
using System;
public class CharDemo
{
public static void Main()
{
Console.Write("請輸入一個字元: ");
char c = (char)Console.Read(); // 讀取單一字元 (含換行符需處理)
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
Console.WriteLine("小寫字母");
else
Console.WriteLine("大寫字母");
}
else if (Char.IsDigit(c))
{
Console.WriteLine("數字字元");
}
else
{
Console.WriteLine("其他符號");
}
}
}
byte → short, ushort, int, uint, long, ulong, float, double, decimal** (單向擴大)
// ✅ 合法隱含轉換
byte b = 100;
int i = b; // byte → int
double d = b; // byte → double
byte x = 100, y = 200;
// ❌ 錯誤:x + y 運算結果為 int,無法隱含指派給 byte
// byte z = x + y;
// ✅ 正確:強制轉型
byte z = (byte)(x + y); // 結果 300 截斷為 44 (溢位行為)
| 分類 | 型別 | 大小 | 範圍/精度 |
|---|---|---|---|
| 整數 | sbyte / byte | 8 bit | -128~127 / 0~255 |
| short / ushort | 16 bit | -32,768~32,767 / 0~65,535 | |
| int / uint | 32 bit | -2.14B~2.14B / 0~4.29B | |
| long / ulong | 64 bit | -9.22E18~9.22E18 / 0~1.84E19 | |
| 浮點數 | float | 32 bit | 7 位有效數字 |
| double | 64 bit | 15-16 位有效數字 | |
| 十進位精確 | decimal | 128 bit | 28-29 位有效數字 (財務計算) |
| 布林 | bool | 1 byte | true / false (不可轉數值) |
| 字元 | char | 16 bit | Unicode UTF-16 |
!= 0, > 0, == true)byte/int 配合 &, |, ^, ~, <<, >>int/long/double 標準大小CS0675 (位元運算於帶號整數) 提早發現問題