需在單一陳述式中完成:依屬性名稱 (a/r/g/b) 將對應值賦給不同變數 (alph/red/green/blue),並處理型別轉換與空值檢查。
foreach (var item in colorJToken)
{
var prop = item as JProperty;
if (prop?.Value == null) continue;
if (prop.Name == "a") alph = (byte)prop.Value;
else if (prop.Name == "r") red = (byte)prop.Value;
else if (prop.Name == "g") green = (byte)prop.Value;
else if (prop.Name == "b") blue = (byte)prop.Value;
}
(prop.Name == "a" ? (alph = (byte)prop.Value) :
prop.Name == "r" ? (red = (byte)prop.Value) :
prop.Name == "g" ? (green = (byte)prop.Value) :
prop.Name == "b" ? (blue = (byte)prop.Value) :
0).ToString(); // 虛假調用避免 "運算結果未使用" 警告
var setters = new Dictionary>
{
["a"] = v => alph = v.Value(),
["r"] = v => red = v.Value(),
["g"] = v => green = v.Value(),
["b"] = v => blue = v.Value()
};
if (setters.TryGetValue(prop.Name, out var setter))
setter(prop);
_ = prop.Name switch
{
"a" => (alph = prop.Value.Value()),
"r" => (red = prop.Value.Value()),
"g" => (green = prop.Value.Value()),
"b" => (blue = prop.Value.Value()),
_ => 0
};
// 假設 JToken 包含 r/g/b/a 屬性,依 BGRA 順序組合為 32-bit 整數
var colorInt = colorJToken.OfType()
.Sum(p => (int)p.Value << "bgra".IndexOf(p.Name) * 8);
var hexColor = colorInt.ToString("X8"); // 如 "FFAABBCC"
原理:"bgra".IndexOf('b')=0 → shift 0;IndexOf('g')=1 → shift 8;IndexOf('r')=2 → shift 16;IndexOf('a')=3 → shift 24。
| 寫法 | 可讀性 | 效能 | 維護性 | 適用場景 |
|---|---|---|---|---|
| if-else | ★★★★★ | ★★★★★ | ★★★★★ | 通用、邏輯複雜 |
| 三元鏈 | ★★☆☆☆ | ★★★★★ | ★★☆☆☆ | 簡單映射、代碼高爾夫 |
| 字典查表 | ★★★★☆ | ★★★★☆ | ★★★★★ | 映射固定、易擴充 |
| Switch Expression | ★★★★★ | ★★★★★ | ★★★★★ | C# 8.0+、模式匹配 |
| 位運算技巧 | ★★☆☆☆ | ★★★★★ | ★★☆☆☆ | 特定領域 (顏色/旗標) |
// 推薦:擴充方法封裝
public static void ApplyColor(this JToken token, ref byte a, ref byte r, ref byte g, ref byte b)
{
var map = new Dictionary>
{
["a"] = v => a = v,
["r"] = v => r = v,
["g"] = v => g = v,
["b"] = v => b = v
};
foreach (var prop in token.OfType())
if (map.TryGetValue(prop.Name, out var action))
action(prop.Value.Value());
}
程式碼的藝術在於恰到好處:用最適合的工具解決問題,而非追求極短行數。