因为我们不能将null值赋给整数类型变量.所以我声明了int?类型变量并使用了三元运算符并试图将变量作为参数传递.但是得到错误.
int? SAP = 0;
SAP = SAP_num == null ? null :Convert.ToInt32(SAP_num);  // SAP_num is string
Run Code Online (Sandbox Code Playgroud)
在尝试这样做时,我收到错误, type of conditional expression can not be determined because there is no implicit conversion betwen '<null>' and 'int'
然后我试了一下
int? SAP = 0;
SAP  = Convert.ToInt32(SAP_num);
int confimation_cd = GetCode(SAP);
Run Code Online (Sandbox Code Playgroud)
在尝试执行此操作时获取错误,GetCode函数接受整数.cannot convert from 'int?' to 'int'
我的问题是,如果SAP_num IS NULL在函数GetCodeelse中传递为null,则传递为整数值.怎么做到这一点?
SAP = SAP_num == null ? (int?)null :Convert.ToInt32(SAP_num);
Run Code Online (Sandbox Code Playgroud)
如果不转换null为int?,则编译器无法为三元运算符的两部分找到公共类型.
BTW它使你的代码更清晰,int.Parse而不是Convert.ToInt32,因为前者只接受一个字符串,而后者可以接受任何基本类型,甚至是Int32!