当dt.Value长度小于4时代码报错,我的修复方案是否可行?
问题分析:数据类型判断代码的修复合理性验证
我的代码在dt.Value不为int时运行正常,但执行dt.Value.ToLower().Substring(0, 4).Equals("date")这行代码时,若dt.Value为int会报错,为varchar或datetime时无异常。我给出了如下修复方案,请问该方案是否合理?
原代码片段
// Edit if (e.CommandName == "Edit") { // Get the item RepeaterItem Item = ((RepeaterItem)((Button)e.CommandSource).NamingContainer); // Get buttons and repeater Button savebtn = (Button)(Item.FindControl("btnSave")); Button editbtn = (Button)(Item.FindControl("btnEdit")); Repeater rFields = (Repeater)(Item.FindControl("repFields")); // Enable my fields foreach (RepeaterItem RI in rFields.Items) { // Get data type HiddenField dt = (HiddenField)(RI.FindControl("hdnDBDataType")); // Set controls if (RI.FindControl("chkSetting").Visible) ((CheckBox)RI.FindControl("chkSetting")).Enabled = true; if (RI.FindControl("ddlSetting").Visible) ((DropDownList)RI.FindControl("ddlSetting")).Enabled = true; if (RI.FindControl("txtSetting").Visible) { ((TextBox)RI.FindControl("txtSetting")).Enabled = true; // Check my data type if (dt.Value.ToLower().Substring(0, 4).Equals("date")) ((CalendarExtender)RI.FindControl("extDateTime")).Enabled = true; } } }
修复方案代码
if(dt.Value != "int" && dt.Value.ToLower().Substring(0, 4).Equals("date"))
修复方案合理性分析
这个方案能解决当前的报错问题,但存在明显局限性:
- 生效原因:当
dt.Value为int时,字符串长度仅为3,调用Substring(0,4)会触发ArgumentOutOfRangeException;添加dt.Value != "int"的判断后,会跳过该危险操作,避免报错。 - 局限性:
- 仅针对
int做了特殊处理,如果后续出现其他长度小于4的数据类型(比如bit),同样会触发相同的越界报错。 - 精确匹配
"int"未考虑大小写问题,若dt.Value是INT或Int,判断会失效,进而执行到Substring导致报错。
- 仅针对
更健壮的优化方案
推荐两种更可靠的写法:
- 先检查字符串长度,再执行截取:
if (dt.Value.Length >= 4 && dt.Value.ToLower().Substring(0, 4).Equals("date"))
- 使用
StartsWith方法(自带长度检查,且支持忽略大小写):
if (dt.Value.StartsWith("date", StringComparison.OrdinalIgnoreCase))
内容的提问来源于stack exchange,提问作者JohnsonBill
相关产品推荐
相关产品推荐

