驗證代碼:列印所有基礎型別 Min/Max/Mid 值
using System;
class MyClass
{
static void Main()
{
// 整數家族
PrintRange("sbyte", sbyte.MinValue, sbyte.MaxValue, (sbyte.MaxValue + sbyte.MinValue) / 2);
PrintRange("byte", byte.MinValue, byte.MaxValue, (byte.MaxValue + byte.MinValue) / 2);
PrintRange("short", short.MinValue, short.MaxValue, (short.MaxValue + short.MinValue) / 2);
PrintRange("ushort", ushort.MinValue, ushort.MaxValue, (ushort.MaxValue + ushort.MinValue) / 2);
PrintRange("int", int.MinValue, int.MaxValue, (int.MaxValue + int.MinValue) / 2);
PrintRange("uint", uint.MinValue, uint.MaxValue, (uint.MaxValue + uint.MinValue) / 2);
PrintRange("long", long.MinValue, long.MaxValue, (long.MaxValue + long.MinValue) / 2);
PrintRange("ulong", ulong.MinValue, ulong.MaxValue, (ulong.MaxValue + ulong.MinValue) / 2);
// 浮點與 decimal
PrintRange("float", float.MinValue, float.MaxValue, (float.MaxValue + float.MinValue) / 2);
PrintRange("double", double.MinValue, double.MaxValue, (double.MaxValue + double.MinValue) / 2);
PrintRange("decimal", decimal.MinValue, decimal.MaxValue, (decimal.MaxValue + decimal.MinValue) / 2);
// char、bool、string
Console.WriteLine("char 類型:");
char c = '萬';
Console.WriteLine($"{c}、{++c}\n");
Console.WriteLine("bool 類型:");
bool b = true;
Console.WriteLine($"{b}、{!b}\n");
Console.WriteLine("string 類型:");
string s = "萬一的 Delphi 博客";
Console.WriteLine($"{s}、Length: {s.Length}\n");
Console.ReadKey();
}
static void PrintRange(string name, dynamic min, dynamic max, dynamic mid)
{
Console.WriteLine($"{name} 類型:");
Console.WriteLine($"{min}、{mid}、{max}\n");
}
}
輸出重點解析
- 有號整數:中間值為 0(對稱範圍)
- 無號整數:中間值為 Max/2
- float/double:MinValue 為 負最大值(非最小正數),Mid 近似 0
- decimal:128 位高精度,適合財務
- char:單一 Unicode 字元,
++c 產生下一碼位
- string:參考型別,
Length 回傳字元數(非位元組)
型別範圍速查表
| 型別 | 位元 | 範圍 | CLR 對應 |
| sbyte | 8 | -128 ~ 127 | System.SByte |
| byte | 8 | 0 ~ 255 | System.Byte |
| short | 16 | -32,768 ~ 32,767 | System.Int16 |
| ushort | 16 | 0 ~ 65,535 | System.UInt16 |
| int | 32 | -2,147,483,648 ~ 2,147,483,647 | System.Int32 |
| uint | 32 | 0 ~ 4,294,967,295 | System.UInt32 |
| long | 64 | -9.22e18 ~ 9.22e18 | System.Int64 |
| ulong | 64 | 0 ~ 1.84e19 | System.UInt64 |
| float | 32 | ±1.5e-45 ~ ±3.4e38 | System.Single |
| double | 64 | ±5.0e-324 ~ ±1.7e308 | System.Double |
| decimal | 128 | ±1.0e-28 ~ ±7.9e28 | System.Decimal |
| char | 16 | U+0000 ~ U+FFFF | System.Char |
| bool | 1 | true/false | System.Boolean |
