我有一个通用的Array2D
类,并且想要添加一个isEmpty
获取器。但在这种情况下,T
无法与default(T)
通过!=
进行比较。并且Equals()
不能使用,因为该字段可能是null
(但请参阅下面的代码)。我如何能够检查所有字段是否为空(即引用类型或结构体等的缺省值)?检查通用数组的空(默认)字段
到目前为止,我提出了以下解决方案,但对于简单的isEmpty
检查,它似乎已经相当冗长,并且它可能不是解决此问题的最佳方法。任何人都知道更好的解决方案?
public sealed class Array2D<T>
{
private T[,] _fields;
private int _width;
private int _height;
public bool isEmpty
{
get
{
for (int x = 0; x < _width; x++)
{
for (int y = 0; y < _height; y++)
{
if (_fields[x, y] != null && !_fields[x, y].Equals(default(T))) return false;
}
}
return true;
}
}
public Array2D(int width, int height)
{
_width = width < 0 ? 0 : width;
_height = height < 0 ? 0 : height;
_fields = new T[width, height];
}
}
我不认为有另一种方式(在性能方面):你仍然需要通过每个元素。也许你可以做一个“foreach”来替换这两个“for”,并用另一种方法进行迭代。 –
如果此特定检查的性能很重要,只需检查“索引器”中的非默认值的分配(但是您已在[i,j]中实现了“set element”) –