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

How to check if int array object is empty in C#?

我有一组整数成绩[5]。 我有一个循环,一个一个地检查数组的对象,看看它们是否为空。 我用过:

if (grades[i] != null)

我收到一条错误消息,指出 int 对象永远不会 "null",因此这个表达式总是 returns "true." 如果不是 "null," 我如何检查数组中的特定对象是否为空?

非常感谢您的帮助!

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

int 是不可为 null 的类型,它的默认值为 0,而不是 null。如果你想要一个允许空值的 int 数组,你可以使用可为空的 int。 int?

你可以这样使用它

int?[] grades = new int?[5];
if (grades[i].HasValue) //The way to check for != null

然后检索值,它不像传统的 int 那样工作。

int gradeValue = grades[i].Value;

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

if (grades[i] != 0)

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

int?[] grades

然后您可以像这样检查单个项目中的空值。

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

根据这个实现,int 应该可以为空。

Nullabele int array is creation can be done using this

int?[] grades = new int?[5];

您可以使用

检查是否有值
grades[i].HasValue

我会考虑做一个验证器class。上面的代码也应该适用于可空类型。

public class ArrayObjectValidator<T>
{
public ArrayObjectValidator(T[] array)
{
    this.array = array;
}

private T[] array { get; set; }

public bool ValidateIndex(int index)
{
    bool result = false;

    if (array != null && array.Length > 0)
    {
        result = CheckItemAt(index);
    }

    return result;
}

private bool CheckItemAt(int index)
{
    return index >= 0 && index < array.Length && NullControl(index);
}

private bool NullControl(int index)
{
    return array[index] != null && array[index] is T;
}
}

您可以如下使用它;

int[] integerArray = new int[10]={1,2,3,4,5,6,7,8,9,0};
ArrayObjectValidator<int> intArrayObjValidator = new ArrayObjectValidator<int>(integerArray);
bool isItemAtIndexFiveNullOrEmpty = integerArray.ValidateIndex(5);