簡體   English   中英

用於約束N維數組的泛型

[英]Generics to constrain an N-dimensional array

有沒有辦法將泛型類型約束為n維數組?

所以, T[]T[,]T[,,] ......等

我基本上試圖將擴展方法添加到我所擁有的任何類型的數組中。 所以我希望使用泛型來獲得這些方法的組合,所以我不需要在里面重復代碼

public static bool IsFull(this MyType[] self) { ... }
public static bool IsFull(this MyType[,] self) { ... }
public static bool IsFull(this MyType[,,] self) { ... }

一種方法看起來像這樣,但應該具有[,][,,]等完全相同的邏輯:

public static bool IsFull(this MyType[] self)
    for (int i=0; i < self.Length; i++) {
        MyType t = self.GetValue(i);
        if (t == null || !t.IsFull()) {
            return false;
        }
    }
    return true;

我相信你最終必須檢查你的數組元素是否是MyType或另一個數組的實例 - 如果這是可以接受的,那么也許你可以在System.Array上添加一個擴展 - 如下所示:

public static class Extension
{
    public static bool IsFull(this Array self)
    {
        for (int i = 0; i < self.Length; i++)
        {
            var t = self.GetValue(i);
            var arrT = t as Array;
            var tt = t as MyType;

            if (t == null || (arrT != null && !arrT.IsFull()) || (tt != null && !tt.IsFull()))
            {
                return false;
            }
        }
        return true;
    }
}

暫無
暫無

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

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