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

C#/.NET 核心 API 速查大全:DateTime、字串、集合、加密、XML、Web 常用片段總整理

     編輯:關於C語言

前言

開發過程中頻繁查閱的 API 片段,整理成分類速查表,涵蓋日期時間、字串操作、型別轉換、集合、編碼、Web 常用、XML、安全性等實戰高頻場景。

一、DateTime 日期時間


var now = DateTime.Now;
var utc = DateTime.UtcNow;

// 取值
int y = now.Year, m = now.Month, d = now.Day;
int h = now.Hour, min = now.Minute, s = now.Second, ms = now.Millisecond;

// 格式化輸出
now.ToString("yyyy-MM-dd HH:mm:ss");   // 2024-01-15 14:30:05
now.ToString("yyyy/MM/dd");            // 2024/01/15
now.ToString("HH:mm");                 // 14:30
now.ToString("o");                     // ISO 8601: 2024-01-15T14:30:05.1234567
now.ToString("r");                     // RFC 1123: Mon, 15 Jan 2024 06:30:05 GMT

// 運算
now.AddDays(10);       // 10 天后
now.AddHours(-3);      // 3 小時前
now.Date;              // 日期部分 (時間歸零)
TimeSpan diff = now - DateTime.Today; // 今日已過時長

// 解析
DateTime.Parse("2024-01-15");
DateTime.TryParse("invalid", out _); // 安全解析
DateTime.ParseExact("15/01/2024", "dd/MM/yyyy", CultureInfo.InvariantCulture);

二、字串核心操作


// 比較
s1.Equals(s2, StringComparison.OrdinalIgnoreCase); // 推薦
string.Compare(s1, s2, true);                      // 相容舊碼

// 搜尋/取代
s.IndexOf("key"); s.LastIndexOf("key");
s.Contains("key"); // .NET Core 2.0+ 有 StringComparison 多載
s.Replace("old", "new");
s.Remove(start, count);
s.Insert(index, "text");

// 分割/合併
s.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
string.Join(",", arr);

// 格式化數值
12345.ToString("N0");   // 12,345
12345.ToString("C");    // $12,345.00 (依文化)
12345.ToString("X");    // 3039 (Hex)
12345.ToString("P");    // 1,234,500.00%

// StringBuilder 高效建構
var sb = new StringBuilder(256); // 預分配容量
sb.AppendLine("Header");
sb.AppendFormat("Id={0}, Name={1}", id, name);
string result = sb.ToString();

三、常用型別轉換


// 字串 <-> 數值
int i = int.Parse("123");
bool ok = int.TryParse("abc", out i); // 安全
double d = Convert.ToDouble("3.14");

// 位元組陣列 <-> 字串
byte[] bytes = Encoding.UTF8.GetBytes("中文");
string s = Encoding.UTF8.GetString(bytes);

// Base64
string b64 = Convert.ToBase64String(bytes);
byte[] back = Convert.FromBase64String(b64);

// Guid
Guid g = Guid.NewGuid();
Guid g2 = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
Guid.Empty; // 空 Guid

四、集合操作精選


// List
list.Add(item);
list.Remove(item);
list.Find(x => x.Id == id);
list.FindAll(x => x.Active);
list.Sort((a,b) => a.Name.CompareTo(b.Name));

// Dictionary
dict.TryGetValue(key, out var value); // 安全取值
dict.GetValueOrDefault(key);          // .NET Core 2.0+
dict.ContainsKey(key);

// LINQ 精華
var active = list.Where(x => x.Active).ToList();
var grouped = list.GroupBy(x => x.Category);
var max = list.Max(x => x.Score);
var firstOrDefault = list.FirstOrDefault(x => x.Id == id);

五、編碼與雜湊


// MD5 / SHA256
using var sha = SHA256.Create();
byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes("password"));
string hex = BitConverter.ToString(hash).Replace("-", "").ToLower();

// HMAC
var hmac = new HMACSHA256(keyBytes);
byte[] sig = hmac.ComputeHash(dataBytes);

六、XML 操作


// LINQ to XML (推薦)
var doc = XDocument.Load("config.xml");
var val = doc.Root.Element("AppSettings").Element("Key").Value;
doc.Root.Element("AppSettings").SetElementValue("Key", "NewValue");
doc.Save("config.xml");

// XmlDocument (舊式)
var xd = new XmlDocument();
xd.Load("config.xml");
XmlNode node = xd.SelectSingleNode("//AppSettings/Key");
node.InnerText = "NewValue";
xd.Save("config.xml");

七、Web / ASP.NET Core 常用


// 取得 Client IP
string ip = context.Connection.RemoteIpAddress?.ToString();
// 含 Proxy
string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault() 
         ?? context.Connection.RemoteIpAddress?.ToString();

// Session
HttpContext.Session.SetString("key", "value");
string val = HttpContext.Session.GetString("key");

// QueryString
string id = Request.Query["id"];

// Redirect
return Redirect("/home");
return RedirectToAction("Index", "Home");

八、檔案與路徑


Path.Combine(dir, "sub", "file.txt");
Path.GetFileName(path);
Path.GetExtension(path);
Path.GetDirectoryName(path);
Path.GetTempFileName();

File.Exists(path);
Directory.Exists(dir);
File.ReadAllText(path, Encoding.UTF8);
File.WriteAllText(path, content, Encoding.UTF8);

九、異常處理模板


try
{
    // 風險程式碼
}
catch (SqlException ex) when (ex.Number == 2627) // 篩選條件
{
    // 唯一鍵衝突
}
catch (Exception ex) when (LogError(ex)) // 條件式捕捉
{
    // 記錄並重拋或處理
}
finally
{
    // 清理資源
}

十、效能微優化清單

  • 熱路徑避免 ToString()、string.Format,改 StringBuilder 或內插字串
  • 避免迴圈中 List.Add 擴容,預估容量 new List(capacity)
  • 結構體 readonly struct 減少複製
  • 使用 Span/Memory 避免陣列切片配置
  • ArrayPool 重用大陣列緩衝區

總結

將此頁加入書籤,下次遇到「DateTime 格式化怎麼寫?」、「Dictionary 安全取值?」、「SHA256 怎麼算?」直接搜尋關鍵字即可。工欲善其事,必先利其器——熟練 API 是高產開發者的基石。

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