【发布时间】:2020-08-19 22:54:06
【问题描述】:
更新了我的 .NET Core 3.1 控制台应用程序以使用 Nullables 功能并具有以下 foreach 循环。
DataTable profiles = DB.ListProfiles();
// CS8600 warning here
// v
foreach (DataRow r in profiles.Rows)
{
// processing code here
}
static public DataTable ListProfiles()
{
DataTable t = new DataTable();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [Table]";
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
sda.Fill(t);
}
}
return t;
}
在本例中,r 有编译器警告。
将 null 文字或可能的 null 值转换为不可为 null 的类型。
我知道需要检查空值等。我的问题是有没有人想出如何使用这个新功能让编译器意识到profiles 和profiles.Rows 都不会为空? ListProfiles 中的 t 变量绝对不会返回任何结果,但这不会使 Rows 为空,对吗?
如果我像这样使用 null-coalescing 运算符 ??:profiles.Rows ?? ... 并且警告会消失,但我无法弄清楚它之后的实际工作是什么。
我也尝试过使用 !来自How to suppress Possible Null Reference warnings 的运算符,但这没有效果。警告仍然存在。虽然这适用于其他类型,但它似乎不适用于 DataRowCollection。
我已经尝试了null 检查的各种位置,但似乎只有明确的代码内抑制有任何效果。
【问题讨论】:
-
@mjwills 这不起作用。添加!
profiles!.Rows的操作员仍然给出警告。