最近在優化歷史包袱的系統, 遇到不少字串拼接或定義不明確或判斷式複雜的程式片段
用以下的小技巧就可以把程式可讀性變高
int temperature = 32;
$"今天氣溫: {temperature} 度";
判斷式檢查, 條件不符就 return, 不要寫成波動拳
if (xxx == false) return;
相同類型單一判斷式 if else 就用 switch case, 甚至可以寫when
public static int DiceSum(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
switch (item)
{
// A single zero value.
case 0:
break;
// A single value.
case int val:
sum += val;
break;
// A non-empty collection.
case IEnumerable<object> subList when subList.Any():
sum += DiceSum(subList);
break;
// An empty collection.
case IEnumerable<object> subList:
break;
// A null reference.
case null:
break;
// A value that is neither an integer nor a collection.
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
若有一筆共用資料不會異動的資料要跑多筆迴圈進行判斷, 建議在迴圈外就將資料從DB讀取並放到記憶體
判斷資料是否null要給預設資料寫法可以簡寫
string userID = userInfo?.userID ?? 0;
Class定義建議一個檔案為一個Class, 不要一個檔案定義多個 Class
與前端UI定義的API接口建議定義ViewModel
固定的型態, 可以用列舉(enum)定義
![]()