擴展代碼:
public static class ClassExtend{/// <summary>/// 將object強制轉化為int/// </summary>/// <param name="o">要強制轉換的object</param>/// <param name="defaultValue">o為null或者轉換失敗的默認值</param>/// <returns></returns>public static int TryToInt(this object o, int defaultValue = 0){int retValue;//o為null 或者轉換失敗返回默認值retValue = o == null || !int.TryParse(o.ToString(), out retValue) ? defaultValue : retValue;return retValue;}}
代碼中使用:
var startIndex = o["StartIndex"].TryToInt(1);
var endIndex = o["EndIndex"].TryToInt(10);
?
常規寫法:
int startIndex;
int endIndex;
startIndex = int.TryParse(o["StartIndex"]?.ToString(), out startIndex) ? startIndex : 1;
endIndex = int.TryParse(o["EndIndex"]?.ToString(), out endIndex) ? endIndex : 10;
?
?