如何在C#中检查int数组对象是否为空?

Nim*_*nai -3 c# arrays int

我有一系列的int等级[5].我有一个循环,一个接一个地检查数组的对象,看看它们是否为空.我用了:

if (grades[i] != null)
Run Code Online (Sandbox Code Playgroud)

我得到一个错误消息,即int对象永远不会为"null",因此该表达式始终返回"true".如果不是"null",我该如何检查数组中的特定对象是否为空?

Thanx很多帮助!

PMe*_*let 5

int不是可空类型.如果您希望能够检查空int,则必须使用可为空的int : int?.


Shi*_*iva 5

我认为你应该检查0像这样的默认值.

if (grades[i] != 0)
Run Code Online (Sandbox Code Playgroud)

但是,如果0在您的用例中是一个有效值并且您希望存储null(即未设置等级),那么您应该将该数组声明为类型为nullable int.像这样.

int?[] grades
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查单个项目中的空值,如此.

if (grades[i].HasValue )
{  
    // mean grades[i] is not null and has some int value inside it
}
Run Code Online (Sandbox Code Playgroud)