如何从另一个 class 引用 3D 数组?

How can I reference a 3D array from another class?

在主程序中class我有:

 static void Main()
 {
    string[,,] anArray = new string [3,3,3];
        anArray[0,0,0] = "value1";
        anArray[0,0,1] = "value2"; .... //filling the rest of the array.
 }

如何使用具有多个参数的构造函数将此数组传递到另一个单独的 class "anotherClass",例如:

 class AnotherClass
 {
 private string[,,] anotherClassArray;

 public string[,,] AnotherClassArray
 {
     get { return anotherClassArray;}
 }

 public AnotherClass (string[,,] fromAnArray)
 {
    anotherClassArray = new string [fromAnArray.Length];
 }
 }

我看过一些示例,其中只有一个简单的一维数组从主程序传递到另一个单独的 class 并再次返回,但是当我尝试对多维执行相同的示例时,我得到了错误:

"Cannot implicitly convert type 'string[]' to 'string[,,*]'" 尝试初始化新数组时。

你可以这样做:

string[, ,] anotherClassArray = new string[anArray.GetLength(0),
                                           anArray.GetLength(1),
                                           anArray.GetLength(2)];

更新

作为一个实验,如果你想让它对任何未知数量的维度通用,你可以使用这个方法:

private Array CreateArrayWithSameDimensions(Array inArray)
{
    int[] lengths = new int[inArray.Rank];
    for (int i = 0; i < inArray.Rank; i++)
    {
        lengths[i] = inArray.GetLength(i);
    }
    Array myArray = Array.CreateInstance(typeof(string), lengths);
    return myArray;
}

这种方法的问题是访问这个数组不像使用已知维度那么简单。这是一个用法示例:

Array myArray = CreateArrayWithSameDimensions(anArray);
int[] indices = new int[anArray.Rank];

for (int i = 0; i < anArray.Rank; i++)
{
       indices[i] = 0;
}

myArray.SetValue("test", indices);

这将在该数组的下限索引中设置 test。如果输入数组是 3 维数组,在 myArray[0,0,0] 中我们将有 test.

如果您希望 AnotherClass 拥有自己独立的空 3D 数组实例,那么您可以按照 Pikoh 所说的进行操作。在这种情况下,如果更改数组的内容,则在 Main 中创建的原始数组不受影响,反之亦然。

如果您希望 AnotherClass 引用与在 Main 中创建的数组相同的数组,因此可以访问相同的填充内容,则只需在 AnotherClass 构造函数中将 AnotherClass.anotherClassArray 引用设置为等于 fromAnArray像这样:

public AnotherClass (string[,,] fromAnArray)
{
   anotherClassArray = fromAnArray;
}