在C#中传递二维数组的一个维度

时间:2012-03-02 09:23:11

标签: c# multidimensional-array

我已经从C转到C#。 我有一个接受数组的函数。我想将一个二维数组的一维传递给这个函数。

C代码将是: -

void array_processing(int * param); 

void main()
{
  int Client_ID[3][50];
  /* Some 
     Processing 
     which fills 
     this array */
    array_processing(&Client_ID[1]);
}

现在,当我想在C#中做同样的事情时,我该如何传递这个数组? 功能定义将如下所示: -

private void array_processing(ref int[] param);

和Array将声明为: -

int[,] Client_ID = new int[3,50];

现在如何将Client_ID[1]传递给函数array_processing() ??

array_processing ( ref Client_ID[1])喊叫为“错误的指数”!

6 个答案:

答案 0 :(得分:7)

你真的不能这样做。 C#对其数组的传递较少,并且阻止您进行类似C的操作。这是一件好事。

您有多种选择:

  1. 创建一维数组并将2D行复制到其中。
  2. 使用锯齿状数组 - 一个数组数组,这更像是C允许你做的事情。
  3. 有一个array_processing重载,它带有一个2D数组和一个行号。

  4. 如果确实想要将2D行作为一维数组访问,则应创建一个“RowProxy”类,该类将实现IList接口并允许您只访问一行: / p>

    class RowProxy<T>: IList<T>
    {
        public RowProxy(T[,] source, int row)
        { 
           _source = source;
           _row = row;
        }
    
        public T this[int col]
        {
            get { return _source[_row, col]; } 
            set { _source[_row, col] = value; }
        }
    
        private T[,] _source;
        private int _row;
    
        // Implement the rest of the IList interface
    }
    
  5. 使用会失去数组语义的lambda表达式,但是很酷:

    var ClientId = ...;
    
    var row_5_accessor = (c=>ClientId[5, c]);
    

    您可以将row_5_accessor用作函数,row_5_accessor(3)将为您提供ClientId[5, 3]

答案 1 :(得分:1)

您可以使用锯齿状数组

// Initialize jagged array
int[][] clientID = new int[3][];
for (int i=0; i<clientId.Length; i++)
{
   clientId[i] = new int[50];
}

array_processing(ref clientId[1]);

你的方法:

private void array_processing(ref int[] subArray);

答案 2 :(得分:0)

只需声明方法

private void ParseArray(int[,] ar)
{
    // Some work...
}
  • UDP:代码格式

答案 3 :(得分:0)

原始方式是:

var dimNumber = 1;

int[] oneDimension = new int[50];

for(var i=0; i<50; i++)
{
   oneDimension[i] = Client_ID[dimNumber][i];
}

array_processing ( ref oneDimension);

我建议像使用zmbq的答案那样使用Lambda表达式。

答案 4 :(得分:0)

您可以将数组声明为

int[][] Client_ID = new[] { new int[50], new int[50], new int[50] };

然后你可以将它传递给你的array_processing函数

array_processing(ref Clinet_ID[1]);

对不起我的笔。

答案 5 :(得分:0)

对话的后期,但这是一个锯齿状的数组示例:

string[][] rows = GetStringArray(values);
string[] row = rows[0];

您可以将锯齿状数组设置为:

// rowCount from runtime data
stringArray = new string[rowCount][];

for (int index = 0; index < rowCount; index++)
{
    // columnCount from runtime data
    stringArray[index] = new string[columnCount];

    for (int index2 = 0; index2 < columnCount; index2++)
    {
        // value from runtime data
        stringArray[index][index2] = value;
    }
}
相关问题