如何在c#中将null值设置为int?

use*_*180 53 .net c# int null nullable

int value=0;

if (value == 0)
{
    value = null;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能设置valuenull上面?

任何帮助将不胜感激.

p.s*_*w.g 86

在.Net中,您无法null为一个int或任何其他结构赋值.相反,使用a Nullable<int>int?简称:

int? value = 0;

if (value == 0)
{
    value = null;
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读


dou*_*lix 77

此外,您不能在条件赋值中使用"null"作为值.例如..

bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;
Run Code Online (Sandbox Code Playgroud)

失败: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.

所以,你必须转换null ...这有效:

int? myint = (testvalue == true) ? 1234 : (int?)null;
Run Code Online (Sandbox Code Playgroud)

  • 优秀.解决了我今晚遇到的一个问题. (3认同)
  • 好吧,这不是问题的答案,但我觉得它非常有用.有人知道这种行为的原因吗? (2认同)

Jon*_*Jon 12

你不能设置intnull.使用可空的int(int?)代替:

int? value = null;
Run Code Online (Sandbox Code Playgroud)