代碼解析
string id = strCurrnetKey.Substring(strCurrnetKey.IndexOf(":") + 1);
逐步執行邏輯
strCurrnetKey.IndexOf(":"):查找冒號 `:` 首次出現的**索引位置** (0 基礎)。若不存在返回 -1。
+ 1:移動到冒號**後一個字符**的位置。
Substring(startIndex):從該位置截取到字符串末尾。
行為對照表
| strCurrnetKey 值 | IndexOf(":") | +1 | Substring 結果 | 說明 |
"user:12345" | 4 | 5 | "12345" | 正常提取冒號後內容 |
"no_colon_here" | -1 | 0 | "no_colon_here" | 無冒號時返回**整個字符串** (IndexOf 返回 -1, +1=0) |
":prefix" | 0 | 1 | "prefix" | 冒號在開頭,提取後綴 |
"suffix:" | 6 | 7 | "" (空字符串) | 冒號在結尾,提取空內容 |
"a:b:c" | 1 | 2 | "b:c" | **僅提取第一個冒號後**的所有內容 |
潛在風險與改進
風險:無冒號時返回整串,可能非預期
// 改進:明確判斷
int idx = strCurrnetKey.IndexOf(":");
string id = (idx >= 0) ? strCurrnetKey.Substring(idx + 1) : strCurrnetKey; // 或返回 null/拋異常
風險:多冒號需求不一致
// 若需最後一個冒號後內容
int lastIdx = strCurrnetKey.LastIndexOf(":");
string id = (lastIdx >= 0) ? strCurrnetKey.Substring(lastIdx + 1) : strCurrnetKey;
// 若需分割所有段
string[] parts = strCurrnetKey.Split(':');
string id = parts.Length > 1 ? parts[1] : parts[0];
性能提示
- `IndexOf` + `Substring` 分配新字符串,高頻調用時考慮 `Span` / `Memory` (C# 7.2+) 避免分配:
ReadOnlySpan span = strCurrnetKey.AsSpan();
int idx = span.IndexOf(':');
ReadOnlySpan idSpan = (idx >= 0) ? span.Slice(idx + 1) : span;
// 後續直接用 idSpan 比較/解析,無需 ToString() 除非必須