[英]How to check if int array object is empty in C#?
I have an array of int grades[5].我有一系列 int 等级 [5]。 I have a loop that checks the objects of the array one by one to see if they're empty.我有一个循环,它一个一个地检查数组的对象,看它们是否为空。 I used:我用了:
if (grades[i] != null)
I get an error message that an int object is never "null" and therefor this expression always returns "true."我收到一条错误消息,指出 int 对象永远不会为“null”,因此该表达式始终返回“true”。 If not "null," how do I check to see if a specific object in the array is empty?如果不是“null”,我如何检查数组中的特定对象是否为空?
Thanx a lot for the help!非常感谢您的帮助!
I think you should check for the default value of 0
like so.我认为您应该像这样检查默认值0
。
if (grades[i] != 0)
However, if 0
is a valid value in your use case and you are expecting to store null
(ie grade not set ) then you should declare the array as of type nullable int
.但是,如果0
在您的用例中是一个有效值并且您希望存储null
(即等级未设置),那么您应该将数组声明为 nullable int
类型。 Like so.像这样。
int?[] grades
Then you can check for null value in individual items like so.然后您可以像这样检查单个项目中的空值。
if (grades[i].HasValue )
{
// mean grades[i] is not null and has some int value inside it
}
int is not a nullable type. int 不是可空类型。 If you want to be able to check an empty int, you must use a nullable int : int?
如果你想能够检查一个空的 int,你必须使用一个可以为 null 的 int : int?
. .
int
is a non-nullable type, instead of being null it will have its default value of 0
. int
是不可为空的类型,它的默认值为0
而不是 null 。 If you want to have an array of int
that allows for nulls you can make use of a nullable int.如果你想要一个允许空值的int
数组,你可以使用一个可为空的 int。 int?
You could use it this way你可以这样使用
int?[] grades = new int?[5];
if (grades[i].HasValue) //The way to check for != null
Then to retrieve the value it does not work like a traditional int
.然后要检索它不像传统的int
那样工作的值。
int gradeValue = grades[i].Value;
int should be nullable according to implement this.根据实现这个,int 应该可以为空。
Nullabele int array is creation can be done using this Nullabele int 数组是创建可以使用这个
int?[] grades = new int?[5];
You can check whether there is value using您可以检查是否有使用价值
grades[i].HasValue
I would consider making a validator class.我会考虑制作一个验证器类。 Code above should be work on nullable types too.上面的代码也应该适用于可空类型。
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;
}
}
you can use it as below;您可以按如下方式使用它;
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.