數據庫列類型為 int,row["ID"] 返回 object,直接與 0 比較編譯報錯或運行異常。
// 1. 安全轉換後比較(推薦)
if (row["ID"] != DBNull.Value && Convert.ToInt32(row["ID"]) == 0) { ... }
// 2. 模式匹配 (C# 7+)
if (row["ID"] is int id && id == 0) { ... }
// 3. 字符串比較(不推薦,有文化差異風險)
if (row["ID"].ToString() == "0") { ... }
row["ID"] == DBNull.Value 為 true。public static class DataRowExtensions {
public static int GetInt(this DataRow row, string col, int defaultValue = 0) {
var val = row[col];
return val == DBNull.Value ? defaultValue : Convert.ToInt32(val);
}
}
// 使用
if (row.GetInt("ID") == 0) { ... }