在C#中传递一个二维数组中的一维 [英] Passing one Dimension of a Two Dimensional Array in C#
问题描述
我已经从C迁移到C#。
我有接受一个数组的功能。我想传递一个二维数组这个功能的一个方面
I have moved from C to C#. I have a function which accepts an array. I want to pass one dimension of a Two Dimensional array to this function.
C代码将是: -
C Code would be:-
void array_processing(int * param);
void main()
{
int Client_ID[3][50];
/* Some
Processing
which fills
this array */
array_processing(&Client_ID[1]);
}
现在,当我想要做在C#一样的,我怎样才能通过这数组?
功能认定中的样子: -
Now, When I want to do same in C#, How can I pass this array? Function defination will look like:-
private void array_processing(ref int[] param);
和数组将被宣布为: -
and Array would be declared as :-
int[,] Client_ID = new int[3,50];
现在如何传递 CLIENT_ID [1]
给函数 array_processing()
??
Now How can I pass Client_ID[1]
to the function array_processing()
??
这样做 array_processing(REF CLIENT_ID [ 1])
呼喊为错指标数!
By doing array_processing ( ref Client_ID[1])
shouts as "Wrong Number of Indices"!
推荐答案
您不能真正做到那。 C#是关于它的阵列少传出,并阻止你做类似C的操作。这是一件好事。
You can't really do that. C# is less outgoing about its arrays, and prevents you from doing C-like manipulations. This is a good thing.
您有多种选择:
- 创建一个一维数组和你的2D行复制到它
- 使用交错数组。 - 数组的数组,这更像是什么C可以让你做
<李>
有一个array_processing重载需要一个二维数组和行号。
- Create a 1D array and copy your 2D row to it.
- Use a jagged array - an array of arrays, which is more like what C lets you do.
Have an array_processing overload that takes a 2D array and a row number.
如果您的真正的要访问二维行作为一维数组,你应该创建,将实现IList接口,并允许您访问只是一个排RowProxy'类:
If you really want to access a 2D row as a 1D array, you should create a 'RowProxy' class that will implement the IList interface and let you access just one row:
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表达式,将失去阵列语义,相反却是酷:
Use a lambda expression that will lose the array semantics, but is rather cool:
var ClientId = ...;
var row_5_accessor = (c=>ClientId[5, c]);
您可以使用row_5_accessor作为一个函数, row_5_accessor(3)
会给你客户端Id [5,3]
You can use row_5_accessor as a function, row_5_accessor(3)
will give you ClientId[5, 3]
这篇关于在C#中传递一个二维数组中的一维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!