Dot-Net

.NET 中的可空整數

  • December 4, 2013

什麼是可空整數,它可以在哪裡使用?

可空整數int?orNullable<int>是 C# 中的值類型,其值可以是nullor 整數值。它預設為null而不是0,並且對於表示諸如value not set(或您希望它表示的任何內容)之類的東西很有用。

可以以多種方式使用可為空的整數。它可以有一個值或空值。像這兒:

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.
}

假設您想知道一個人的年齡。如果該人已送出他的年齡,則它位於數據庫中。

int? age = GetPersonAge("Some person");

如果像大多數女性一樣,這個人沒有送出他/她的年齡,那麼數據庫將包含 null。

然後檢查 的值age

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

引用自:https://stackoverflow.com/questions/2735638