我已经从 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);
数组将被声明为:-
int[,] Client_ID = new int[3,50];
现在我怎样才能通过Client_ID[1]
到函数array_processing()
??
通过做array_processing ( ref Client_ID[1])
喊“索引数量错误”!
你真的不能那样做。 C# 对于数组不太外向,并且阻止您进行类似 C 的操作。这是一件好事。
您有多种选择:
- 创建一个一维数组并将二维行复制到其中。
- 使用锯齿状数组 - 数组的数组,这更像是 C 允许您做的事情。
有一个 array_processing 重载,它接受一个 2D 数组和一个行号。
-
If you really想要将 2D 行作为 1D 数组访问,您应该创建一个“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
}
-
使用 lambda 表达式会丢失数组语义,但相当酷:
var ClientId = ...;
var row_5_accessor = (c=>ClientId[5, c]);
您可以使用 row_5_accessor 作为函数,row_5_accessor(3)
会给你ClientId[5, 3]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)