简体   繁体   English

修改多维数组

[英]Modify multi Dimensional array

I have an Array variable. 我有一个数组变量。 I can use the Rank property to get the number of dimensions and I know that you can use a foreach to visit each element as if the array was flattened. 我可以使用Rank属性来获取维数,并且我知道您可以使用foreach来访问每个元素,就好像数组被展平了一样。 However, I wish to modify elements and change element references. 但是,我希望修改元素并更改元素引用。 I cannot dynamically create the correct number of for loops and I cannot invalidate an enumerator. 我无法动态创建正确数量的for循环,也无法使枚举数无效。

EDIT Thanks for the comments, sorry about the previous lack of clarity at the end of a long tiring day. 编辑感谢您的评论,对于冗长的一天结束后以前的不清晰表示歉意。 The problem: 问题:

private void SetMultiDimensionalArray(Array array)
{
    for (int dimension = 0;  dimension < array.Rank;   dimension++)
    {
        var len = array.GetLength(dimension);
        for (int k = 0; k < len; k++)
        {
            //TODO: do something to get/set values
        }
     }
}

Array array = new string[4, 5, 6];
SetMultiDimensionalArray(array);
Array array = new string[2, 3];
SetMultiDimensionalArray(array);

I had another look before reading this page and it appears all I need to do is create a list of integer arrays and use the overloads of GetValue and SetValue - 在阅读此页面之前,我有另一种眼神,看来我需要做的就是创建一个整数数组列表并使用GetValue和SetValue的重载-

Array.GetValue(params int[] indices)
Array.SetValue(object value, params int[] indices)

Everything seems clear now unless someone can suggest a superior method. 除非有人可以提出更好的方法,否则现在一切似乎都很清楚。 svick has linked to this so I will accept this answer barring any further suggestions. svick已与此链接,所以除非有其他建议,否则我将接受此答案。

It's hard to tell what exactly do you need, because your question is quite unclear. 很难说出您到底需要什么,因为您的问题还不清楚。

But if you have a multidimensional array (not jagged array) whose rank you know only at runtime, you can use GetValue() to get the value at specified indices (given as an array of int s) and SetValue() to set it. 但是,如果有一个仅在运行时才知道其等级的多维数组(而不是锯齿状数组),则可以使用GetValue()获取指定索引处的值(作为int数组),并使用SetValue()进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM