是否有可能获得"坐标"一个基于它的索引的元素?

时间:2014-03-14 16:02:54

标签: c# multidimensional-array

我有一个字符串[5,5]数组。是否可以根据它的索引来计算元素的位置,假设它总是一个5x5矩阵?

按位置我的意思是元素在给定数组中的笛卡尔坐标。

2 个答案:

答案 0 :(得分:1)

简答 - 是的

详细答案 - “基于它们的索引,可以从运行时数组类型实例的内存位置直接访问或修改单维和锯齿状数组元素。为此,CLR提供了一个名为ldelem和stelem的特殊IL指令,它基于数组元素检索和修改数组元素。它的索引和数组Object Reference在堆栈上可用。而多维数组元素是使用对数组类型的合成运行时类型的方法调用来访问或修改的。这使得锯齿状数组比多维数组快得多,并且推荐使用在需要多个维度的情况下使用数组.Jagged数组符合CLS,并且被错误地记录为NOT CLS兼容。这一事实在MSDN2中得到承认。“

http://www.codeproject.com/KB/cs/net_type_internals.aspx?fid=459323&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2567811

复制

答案 1 :(得分:1)

也许一个简单的扩展方法会有所帮助:

public static class Extensions
{
    public static void FindCoordinates<T>(this T[,] source, int index, out int x,out int y)
    {
        int counter = 0;
        for (int i = 0; i < source.GetLength(0); i++)
        {
            for (int j = 0; j < source.GetLength(1); j++)
            {
                counter++;
                if (counter == index)
                {
                    x = i;
                    y = j;
                    return;
                }
            }
        }

        x = -1;
        y = -1;
    }
}

用法:

int[,] array = new int[5,5];

int x, y;
array.FindCoordinates(5,out x,out y);
Console.WriteLine("x = {0} y = {1}", x, y);  // x = 0 y = 4

array.FindCoordinates(7,out x,out y);
Console.WriteLine("x = {0} y = {1}", x, y); // x = 1 y = 1