将空值传递给int



因为我们不能给整型变量赋空值。因此,我声明了int?类型变量,并使用三元运算符,并试图将变量作为参数传递。

int? SAP = 0;
SAP = SAP_num == null ? null :Convert.ToInt32(SAP_num);  // SAP_num is string

当尝试这样做时,我得到错误, type of conditional expression can not be determined because there is no implicit conversion betwen '<null>' and 'int'

Then I try

int? SAP = 0;
SAP  = Convert.ToInt32(SAP_num);
int confimation_cd = GetCode(SAP);

当尝试这样做得到错误, cannot convert from 'int?' to 'int'

我的问题是,如果SAP_num IS NULL在函数GetCode中传递为空,则传递为整数值。如何做到这一点?

SAP = SAP_num == null ? (int?)null :Convert.ToInt32(SAP_num);

如果不将null转换为int?,编译器无法为三元操作符的两个部分找到通用类型。

顺便说一句,使用int.Parse而不是Convert.ToInt32会让你的代码更清晰,因为前者只接受字符串,而后者可以接受任何基本类型,甚至是Int32!

您可以创建这样一个扩展函数:

public static class StringExt
{
    public static int? ConvertToNullableInt(this string str)
    {
        int temp;
        if (int.TryParse(str, out temp))
            return temp;
        return null;
    }
}

并像这样使用:

string SAP_num = null;
int? SAP = SAP_num.ConvertToNullableInt();

最新更新