C# :从函数返回 dbnull.value 或 system.type

本文关键字:value system type dbnull 返回 函数 | 更新日期: 2023-09-27 17:55:16

我想创建一个函数(c#):

int PutInt (int? x)
{
    if (x.HasValue)
        return x.Value;
    else
        return DBNull.Value;
}

但是没有从int到DBNull.Value的转换。有没有办法创建这样的函数?

C# :从函数返回 dbnull.value 或 system.type

假设你的DBMS是SQLServer,你可以将你的函数转换为

object PutInt (int? x)
{
    if (x.HasValue)
        return (object)x.Value;
    else
        return (object)DBNull.Value;
}

因为 SQLParamater 值属性假定类型对象。希望我回答你的问题。

这本质上是不可能的 - 值类型不能为空。

你需要使用一个可为空的类型(int?),这使得你的函数完全无用。

不,你不能把int投到DBNull.Value。这用于计算数据库字段的内容,而不是可为 null 的类型。可为空类型的值只需null

比您定义的函数更好的选择是使用 null 合并运算符?? )。

它的逻辑与您尝试在函数中构造的逻辑非常相似。请考虑以下代码行:

// Declare a nullable int, and set it to null
int? x = null;
// Assign int y to x, unless x is null, in which case, set y = -1
int y = x ?? -1;
// The variable y now has a value of -1
Console.WriteLine(y);

如果您只是分配给对象变量类型,我建议您忘记使用该方法而只使用条件赋值

 object obj = (x.HasValue? x.Value : DBNull.Value);