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

Swa*_*and 3 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]);
}
Run Code Online (Sandbox Code Playgroud)

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

private void array_processing(ref int[] param);
Run Code Online (Sandbox Code Playgroud)

和Array将声明为: -

int[,] Client_ID = new int[3,50];
Run Code Online (Sandbox Code Playgroud)

现在我怎样才能传递Client_ID[1]给函数array_processing()

通过array_processing ( ref Client_ID[1])喊叫"错误的指数"!

zmb*_*mbq 7

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

你有各种选择:

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

  4. 如果你真的想要将2D行作为一维数组访问,你应该创建一个'RowProxy'类来实现IList接口并让你只访问一行:

    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
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 使用一个会失去数组语义的lambda表达式,但是很酷:

    var ClientId = ...;
    
    var row_5_accessor = (c=>ClientId[5, c]);
    
    Run Code Online (Sandbox Code Playgroud)

    你可以使用row_5_accessor作为函数,row_5_accessor(3)给你ClientId[5, 3]