簡體   English   中英

檢查通用數組是否為空(默認)字段

[英]Check generic Array for empty (default) fields

我有一個通用的Array2D類,想添加一個isEmpty getter。 但是T無法比擬的default(T)通過!=在這種情況下。 並且Equals()不能使用,因為該字段可能為null (但請參見下面的代碼)。 如何檢查所有字段是否為空(即引用類型或struct / etc的默認值)?

到目前為止,我想出了以下解決方案,但是對我來說,進行簡單的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];
    }
}

無需遍歷IsEmpty所有元素,只需在設置值時更新IsEmpty的值即可(需要一個索引器,但無論如何您可能都需要一個):

public class Array2<T>
{
    private readonly T[,] _array;
    private bool _isEmpty;

    public Array2(int width, int height)
    {
        _array = new T[width, height];
        _isEmpty = true;
    }

    public T this[int x, int y]
    {
        get { return _array[x, y]; }
        set
        {
            _array[x, y] = value;
            _isEmpty = _isEmpty && value.Equals(default(T));
        }
    }

    public bool IsEmpty
    {
        get { return _isEmpty; }
    }
}

例:

Array2<int> array2 = new Array2<int>(10, 10);
array2[0, 0] = 0;
Console.WriteLine(array2.IsEmpty);
array2[0, 0] = 1;
Console.WriteLine(array2.IsEmpty);
array2[0, 0] = 0;
Console.WriteLine(array2.IsEmpty);

輸出:

True
False
False

顯然,這是一個折衷方案,但是可以想象一下,如果數組中有100萬個元素,則循環將運行100萬次。 使用這種方法沒有循環,可以隨時檢查2個條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM