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

C# 類型轉換全攻略:別名、裝箱拆箱、數值轉換、字符編碼、日期格式化

     編輯:關於C語言

1. 基礎類型別名對照表

C# 關鍵字實為結構體別名,編譯後均為對應結構體:

關鍵字結構體說明
boolSystem.Booleantrue/false
byteSystem.Byte0~255
sbyteSystem.SByte-128~127
charSystem.CharUnicode 字符
shortSystem.Int16-32,768~32,767
ushortSystem.UInt160~65,535
intSystem.Int32-2.1B~2.1B
uintSystem.UInt320~4.2B
longSystem.Int64±9.22E18
ulongSystem.UInt640~1.84E19
floatSystem.Single7位精度
doubleSystem.Double15-16位精度
decimalSystem.Decimal28-29位精度,貨幣首選

驗證代碼:typeof(int) == typeof(System.Int32) → true

2. 隱式/顯式數值轉換

  • 隱式擴大:byte → short → int → long → float → double(無數據丟失)
  • 顯式縮小:需強制轉換 (targetType)value,可能溢出或精度損失
  • 檢查溢出:checked 上下文拋出 OverflowException

3. 字符與編碼互轉


// 字符 → 編碼
char ch = 'A';
int ascii = (int)ch; // 65
char cn = '中';
int unicode = (int)cn; // 20013

// 編碼 → 字符
char fromAscii = (char)65; // 'A'
char fromUnicode = (char)20013; // '中'

4. 字符串與數值互轉

  • 數值 → 字符串:value.ToString()、string.Format、$"{value}"
  • 字符串 → 數值:int.Parse("123")、int.TryParse(推薦,避免異常)、Convert.ToInt32

5. 字符串與字符/字節數組

轉換方法
String → char[]str.ToCharArray()
char[] → Stringnew string(charArray)
String → byte[]Encoding.UTF8.GetBytes(str)
byte[] → StringEncoding.UTF8.GetString(bytes)

常用編碼:Encoding.Default (ANSI)、Encoding.Unicode (UTF-16 LE)、Encoding.UTF8、Encoding.ASCII

6. 結構體與字節數組


byte[] bytes = BitConverter.GetBytes(12345); // int → 4 bytes
int value = BitConverter.ToInt32(bytes, 0);  // 4 bytes → int

7. 十六進制格式化


int val = 188;
val.ToString("X");   // "BC"
val.ToString("X4");  // "00BC" (寬度4,前導0)
int parsed = int.Parse("BC", NumberStyles.HexNumber); // 188

8. DateTime 與長整型/雙精度互轉

  • Ticks:從 0001-01-01 00:00:00 起的 100ns 間隔數,long ticks = dt.Ticks,new DateTime(ticks)
  • OLE Automation Date (VB6 兼容):double oa = dt.ToOADate(),DateTime.FromOADate(oa)

9. DateTime 格式化字符串

符號含義示例
yyyy四位年2024
MM兩位月01~12
dd兩位日01~31
HH24制時00~23
mm分00~59
ss秒00~59
fff毫秒000~999

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 2024-01-15 14:30:45
DateTime.Now.ToString("'Year:' yyyy 'Month:' MM"); // Year: 2024 Month: 01

字面量文字用單引號或雙引號包裹。

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