如何在方法中提供可为空的参数?

how fo feed a nullable parameter in a method?

我有一个方法可以接受可为 null 的参数,因为它是从 table 中用可为 null 的列填充的。

private void test(int ID, int? value)
{}

调用此方法时,我需要某种方法为其提供可为空的变量,这就是我的问题。 我试过了:

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int?)row["value"]);
}

但它给了我一个转换错误

"specified cast is not valid"

所以我尝试了这个:

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int)row["value"] ?? DBnull.Value);
}  

还有这个:

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int)row["value"] ?? null);
}

但他们都给我错误

"Operator ?? cannot be applied to operands of type int and null

我最后试的是这个:

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int?)row["value"] ?? null);
}

这个可以编译但给出运行时错误

"specified cast is not valid"

那我该怎么做呢? 这个想法是参数值填充 table 中的值或 null.

您可以使用支持可空类型的 DataRow 扩展方法 Field

foreach (DataRow row in DataTable1.Rows)
{
    int id = row.Field<int>("ID");
    int? value = row.Field<int?>("value");
    test(id, value);
}

尝试使用 as(如果失败则 returns null 的安全转换):

test((int)row["ID"], row["value"] as int?);
foreach (DataRow row in DataTable1.Rows)
{
   var id = row["ID"] as int? ??default(int);
   int? value = row["value"] as int? ??default(int?);

   test(id, value);
}