首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 型別轉換完全指南:從裝箱拆箱到日期格式化的實戰詳解

     編輯:關於C語言

一、別名與裝箱/拆箱的真相

C# 的基本型別(int、double、bool 等)實際上是結構體,對應 System.Int32、System.Double、System.Boolean 等類型。所謂「裝箱/拆箱」實際上是值型別與 object 之間的轉換,而 int ⇄ Int32 僅是編譯期的別名關係,零成本:

int a = 1;
Console.WriteLine(a.GetType().FullName); // System.Int32

常用別名對照表:

關鍵字完整型別大小/範圍
boolSystem.Booleantrue/false
byteSystem.Byte0~255
sbyteSystem.SByte-128~127
charSystem.CharUTF-16 字元
shortSystem.Int16-32,768~32,767
ushortSystem.UInt160~65,535
intSystem.Int32-2,147,483,648~2,147,483,647
uintSystem.UInt320~4,294,967,295
longSystem.Int64±9.22×10¹⁸
ulongSystem.UInt640~1.84×10¹⁹
floatSystem.Single7 位有效數字
doubleSystem.Double15-16 位有效數字
decimalSystem.Decimal28-29 位有效數字,金融首選

二、數值型別隱式與顯式轉換

隱式轉換(資料不會遺失):byte → short → int → long → float → double

byte b = 100;
int i = b;        // 隱式
long l = i;       // 隱式

顯式轉換(可能遺失資料或溢位):

int i = 300;
byte b = (byte)i; // 44 (300 % 256) - 溢位截斷!

檢查溢位:使用 checked 區塊或編譯選項 /checked+ 讓溢位拋出 OverflowException。

三、字元與編碼互轉

char c = 'A';
int ascii = (int)c;        // 65
char fromCode = (char)65;  // 'A'

char chinese = '中';
int unicode = (int)chinese; // 20013 (0x4E2D)

四、字串與數值互轉

// 數值 → 字串
string s1 = 123.ToString();
string s2 = 3.14.ToString("F2"); // "3.14"
string hex = 255.ToString("X4"); // "00FF"

// 字串 → 數值
int i = int.Parse("123");
double d = double.Parse("3.14", CultureInfo.InvariantCulture);
bool success = int.TryParse("abc", out int result); // 安全轉換

五、字串、字元陣列、位元組陣列互轉

string text = "Hello";
// 字串 → char[]
char[] chars = text.ToCharArray();
// char[] → 字串
string fromChars = new string(chars);

// 字串 → byte[] (指定編碼)
byte[] utf8Bytes = Encoding.UTF8.GetBytes(text);
byte[] big5Bytes = Encoding.GetEncoding("big5").GetBytes(text);
// byte[] → 字串
string fromUtf8 = Encoding.UTF8.GetString(utf8Bytes);

六、BitConverter:基本型別與位元組陣列互轉

int value = 0x01020304;
byte[] bytes = BitConverter.GetBytes(value); // 小端序:04 03 02 01
int restored = BitConverter.ToInt32(bytes, 0);

七、十六進制格式化與解析

int n = 188;
Console.WriteLine(n.ToString("X"));    // "BC"
Console.WriteLine(n.ToString("X4"));   // "00BC"

int parsed = int.Parse("BC", NumberStyles.HexNumber); // 188

八、DateTime 與 Ticks / OADate 互轉

// DateTime → long (Ticks: 100ns 間隔從 0001-01-01 起算)
long ticks = DateTime.Now.Ticks;
DateTime dt = new DateTime(ticks);

// DateTime ↔ Double (OLE Automation Date: 從 1899-12-30 起算的天數)
double oaDate = DateTime.Now.ToOADate();
DateTime fromOA = DateTime.FromOADate(oaDate);

九、DateTime 格式化完整指南

DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss")); // 2024-01-15 14:30:45
Console.WriteLine(now.ToString("yyyy年M月d日"));       // 2024年1月15日

// 包含字面文字需用單引號跳脫
Console.WriteLine(now.ToString("'Year:' yyyy 'Month:' MM")); // Year: 2024 Month: 01

常用格式字元:y/M/d(無前導零)、yy/MM/dd(有前導零)、HH/mm/ss(24小時制)、hh/mm/ss(12小時制)、fff(毫秒)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved