.NET中可以为Null的整数

Xul*_*fee 8 .net types nullable

什么是可以为空的整数?它可以在哪里使用?

Håv*_*d S 17

可以为null的整数int?或者Nullable<int>是C#中的值类型,其值可以是null整数值.它默认null代替0,而且对于表示像value not set(或者你想要它表示的任何东西)这样的东西很有用.


San*_*nen 8

可以以各种方式使用可以为空的整数.它可以有一个值或null.像这儿:

int? myInt = null;

myInt = SomeFunctionThatReturnsANumberOrNull()

if (myInt != null) {
  // Here we know that a value was returned from the function.
}
else {
  // Here we know that no value was returned from the function.
}
Run Code Online (Sandbox Code Playgroud)

假设你想知道一个人的年龄.如果此人提交了他的年龄,它位于数据库中.

int? age = GetPersonAge("Some person");
Run Code Online (Sandbox Code Playgroud)

如果像大多数女性一样,这个人没有提交他/她的年龄,那么数据库将包含null.

然后你检查以下值age:

if (age == null) {
  // The person did not submit his/her age.
}
else {
  // This is probably a man... ;)
}
Run Code Online (Sandbox Code Playgroud)