简体   繁体   中英

C#: Passing generic arrays

I am trying to write a method that checks, if a given x/y pair is a valid index for a 2nd array (eg check if myArray[x,y] is safe).

I would like it to work with arrays of any type, which I feel should be possible because they all have the same GetUpperBounds(int d) method and I do not need to touch their contents. I have tried

bool validate(<T>[,] array, int x, int y){ ... }

and

bool validate([,] array, int x, int y){ ... }

but that does not work.

Should I just keep overloading this method as needed even though the method bodies will be identical character for character?

The right syntax is:

bool validate<T>(T[,] array, int x, int y)
{
}

with the code inside that should be:

bool validate<T>(T[,] array, int x, int y)
{
    return x >= array.GetLowerBound(0) && x <= array.GetUpperBound(0) &&
        y >= array.GetLowerBound(1) && y <= array.GetUpperBound(1);
}

Or ignoring array that have a lower bound != 0... (you can create arrays that have the first index at 100, so that myarray[100] is the first element. It was done for compatibility with old VB probably. It isn't very used)

bool validate<T>(T[,] array, int x, int y)
{
    return x >= 0 && x < array.GetLength(0) &&
        y >= 0 && y < array.GetLength(1);
}

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