首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 常用函式速查手冊:日期時間、字串操作、編碼轉換、XML 操作完整整理

     編輯:C# 入門

前言:高頻 API 集中查閱

整理 C# 開發中最高頻的基礎類別庫用法,涵蓋 DateTime、字串處理、編碼、XML、集合等核心場景,作為開發時的快速參考卡。

一、DateTime 日期時間操作


// 當前時間
DateTime now = DateTime.Now;
DateTime utcNow = DateTime.UtcNow;

// 元件存取
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
int ms = now.Millisecond;
DayOfWeek dow = now.DayOfWeek;

// 格式化輸出
string full = now.ToString("F");      // 完整日期時間 (長日期+長時間)
string shortDate = now.ToString("d"); // 短日期 2024/01/15
string longDate = now.ToString("D");  // 長日期 2024年1月15日
string shortTime = now.ToString("t"); // 短時間 14:30
string longTime = now.ToString("T");  // 長時間 14:30:25
string custom = now.ToString("yyyy-MM-dd HH:mm:ss.fff");

// 常用格式字串
// yyyy 年份, MM 月份, dd 日, HH 24小時, mm 分鐘, ss 秒, fff 毫秒
// MMMM 月份名稱, ddd 週幾縮寫, dddd 週幾全名

// 解析字串
DateTime parsed = DateTime.Parse("2024-01-15 14:30:00");
bool success = DateTime.TryParse("invalid", out DateTime result);

// 日期運算
DateTime tomorrow = now.AddDays(1);
DateTime lastWeek = now.AddDays(-7);
DateTime nextMonth = now.AddMonths(1);
TimeSpan diff = DateTime.Now - new DateTime(2024,1,1);
double totalDays = diff.TotalDays;

// 週期計算
DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek); // 週日為起始
DateTime startOfMonth = new DateTime(now.Year, now.Month, 1);

二、字串核心操作

基本屬性與檢查


string s = "Hello World";
int len = s.Length;                    // 字元長度
bool empty = string.IsNullOrEmpty(s);  // null 或 ""
bool white = string.IsNullOrWhiteSpace(s); // null、空白、空字串
bool starts = s.StartsWith("He");      // 前綴
bool ends = s.EndsWith("ld");          // 後綴
bool contains = s.Contains("lo");      // 包含
bool equals = s.Equals("hello", StringComparison.OrdinalIgnoreCase); // 忽略大小寫比較

搜尋與索引


int idx = s.IndexOf("l");        // 首次出現索引 (2)
int last = s.LastIndexOf("l");   // 最後出現索引 (9)
int idxFrom = s.IndexOf("o", 5); // 從索引 5 開始找

子字串與分割


string sub = s.Substring(6);       // "World" (從索引 6 到結尾)
string sub2 = s.Substring(6, 3);   // "Wor" (長度 3)
string[] parts = s.Split(' ');     // ["Hello", "World"]
string[] lines = text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

修剪與替換


string trimmed = s.Trim();              // 移除首尾空白
string trimStart = s.TrimStart();       // 移除開頭空白
string trimEnd = s.TrimEnd();           // 移除結尾空白
string replaced = s.Replace("World", "C#"); // "Hello C#"
string removed = s.Replace("l", "");    // "Heo Word"

大小寫轉換


string upper = s.ToUpper();       // "HELLO WORLD"
string lower = s.ToLower();       // "hello world"
string title = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower()); // "Hello World"

格式化與插值


string fmt = string.Format("{0:C}", 1234.5); // "NT$1,234.50" (依文化特性)
string interp = $"{DateTime.Now:yyyy-MM-dd} 價格: {1234.5:C}"; // C# 6+ 插值字串
string composite = $"姓名: {name}, 年齡: {age:D3}"; // 格式化規格

StringBuilder 高效建構


var sb = new StringBuilder();
sb.Append("第一行").AppendLine();
sb.AppendFormat("數值: {0:N2}", 1234.5).AppendLine();
sb.AppendJoin(", ", new[] { "A", "B", "C" });
string result = sb.ToString();

三、編碼與位元組轉換


string text = "中文測試";

// 字串 -> 位元組陣列
byte[] utf8Bytes = Encoding.UTF8.GetBytes(text);
byte[] big5Bytes = Encoding.GetEncoding(950).GetBytes(text);
byte[] defaultBytes = Encoding.Default.GetBytes(text); // 系統預設 (繁中環境通常 Big5)

// 位元組陣列 -> 字串
string fromUtf8 = Encoding.UTF8.GetString(utf8Bytes);
string fromBig5 = Encoding.GetEncoding(950).GetString(big5Bytes);

// Base64 編碼
string base64 = Convert.ToBase64String(utf8Bytes);
byte[] fromBase64 = Convert.FromBase64String(base64);

// 位元組長度
int byteLen = utf8Bytes.Length;

四、數值轉換與格式化


// 字串 -> 數值
int i = int.Parse("123");
bool ok = int.TryParse("abc", out int result);
double d = double.Parse("3.14");
decimal m = decimal.Parse("123.45");

// 數值 -> 格式化字串
string n1 = 12345.ToString("N");      // "12,345.00" 千分位
string n2 = 12345.ToString("C");      // "NT$12,345.00" 貨幣
string n3 = 12345.ToString("E");      // "1.234500E+004" 科學記號
string n4 = 12345.ToString("F4");     // "12345.0000" 固定小數
string n5 = 12345.ToString("X");      // "3039" 十六進位
string n6 = 12345.ToString("P");      // "1,234,500.00%" 百分比
string n7 = 12345.ToString("000000"); // "012345" 補零

// 進制轉換
string bin = Convert.ToString(255, 2);  // "11111111" 二進位
string hex = Convert.ToString(255, 16); // "FF" 十六進位
int fromHex = Convert.ToInt32("FF", 16); // 255

五、集合與 LINQ 精選


var list = new List { 1, 2, 3, 4, 5 };

// 篩選
var evens = list.Where(x => x % 2 == 0).ToList(); // [2, 4]

// 投影
var squares = list.Select(x => x * x).ToList(); // [1, 4, 9, 16, 25]

// 聚合
int sum = list.Sum();
int max = list.Max();
double avg = list.Average();

// 分組
var people = new[] { new { Name="A", Dept="IT" }, new { Name="B", Dept="HR" } };
var byDept = people.GroupBy(p => p.Dept);

// 排序
var sorted = list.OrderByDescending(x => x).ToList();

// 任意/所有
bool any = list.Any(x => x > 3); // true
bool all = list.All(x => x > 0); // true

// 字典操作
var dict = new Dictionary { ["A"] = 1, ["B"] = 2 };
dict.TryGetValue("A", out int val); // 安全取值
dict.GetValueOrDefault("C", 0);     // 不存在回傳預設值

六、XML 基礎操作 (LINQ to XML)


using System.Xml.Linq;

// 建立 XML
XElement root = new XElement("Books",
    new XElement("Book",
        new XAttribute("id", 1),
        new XElement("Title", "C# 入門"),
        new XElement("Author", "張三"),
        new XElement("Price", 450)
    ),
    new XElement("Book",
        new XAttribute("id", 2),
        new XElement("Title", "進階 .NET"),
        new XElement("Author", "李四"),
        new XElement("Price", 680)
    )
);

// 存檔
root.Save("books.xml");

// 讀取與查詢
XDocument doc = XDocument.Load("books.xml");
var titles = doc.Descendants("Book")
    .Where(b => (int)b.Element("Price") > 500)
    .Select(b => b.Element("Title").Value);

// 新增節點
root.Add(new XElement("Book", 
    new XAttribute("id", 3),
    new XElement("Title", "新書"),
    new XElement("Price", 300)
));

// 修改
var book1 = root.Element("Book");
book1.Element("Price").SetValue(500);

// 刪除
book1.Remove();

七、檔案與目錄速查


using System.IO;

// 路徑操作
string full = Path.GetFullPath("test.txt");
string dir = Path.GetDirectoryName(full);
string name = Path.GetFileName(full);
string ext = Path.GetExtension(full);
string noExt = Path.GetFileNameWithoutExtension(full);
string combined = Path.Combine(dir, "sub", "file.txt");

// 檔案操作
bool exists = File.Exists("test.txt");
File.Copy("src.txt", "dest.txt", true); // true=覆蓋
File.Move("old.txt", "new.txt");
File.Delete("temp.txt");
byte[] data = File.ReadAllBytes("data.bin");
string text = File.ReadAllText("readme.txt", Encoding.UTF8);
File.WriteAllText("out.txt", "內容", Encoding.UTF8);
File.AppendAllLines("log.txt", new[] { "行1", "行2" });

// 目錄操作
Directory.CreateDirectory(@"C:\Data\Logs");
string[] files = Directory.GetFiles(@"C:\Data", "*.log", SearchOption.AllDirectories);
string[] dirs = Directory.GetDirectories(@"C:\Data");
Directory.Delete(@"C:\Temp", true); // true=遞迴刪除

// 串流讀寫 (大檔案)
using (var fs = new FileStream("big.dat", FileMode.Open, FileAccess.Read))
using (var reader = new BinaryReader(fs))
{
    // 逐塊讀取
}

八、常用數學與隨機


// Math
double sqrt = Math.Sqrt(16);      // 4
double pow = Math.Pow(2, 10);     // 1024
double abs = Math.Abs(-3.14);     // 3.14
double ceil = Math.Ceiling(3.2);  // 4
double floor = Math.Floor(3.8);   // 3
double round = Math.Round(3.5);   // 4 (銀行家算法)
int max = Math.Max(10, 20);       // 20
int min = Math.Min(10, 20);       // 10
double log = Math.Log(10);        // 自然對數
double sin = Math.Sin(Math.PI/2); // 1

// Random
var rnd = new Random();
int dice = rnd.Next(1, 7);        // 1-6
double prob = rnd.NextDouble();   // 0.0-1.0
byte[] buffer = new byte[16];
rnd.NextBytes(buffer);            // 隨機位元組

// 密碼學隨機 (安全性需求)
using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create())
{
    byte[] secure = new byte[32];
    rng.GetBytes(secure);
}

結語

本手冊彙整 C# 開發最高頻的基礎類別庫用法,涵蓋日期時間、字串、編碼、數值格式化、集合 LINQ、XML、檔案目錄、數學隨機八大領域。建議開發者建立個人片段庫,搭配 IDE 程式碼片段功能,實現真正的「指尖查閱」。

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