简体   繁体   中英

Generics to constrain an N-dimensional array

Is there a way to constrain a generic type to be an n-dimensional array?

So, T[] , T[,] , T[,,] , ... etc.

I'm basically trying to add an extension method to any type of arrays of that type I have. So I'm looking to get a combination of these methods using generics so I don't need to repeat the code inside

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

One method looks like this, but should have the exact same logic for [,] , [,,] etc:

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;

I believe you'll eventually have to check if your array element is an instance of MyType or another array - if that's acceptable then perhaps you can add an extension on System.Array - something like this:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM