c# - 如何从另一个类引用 3D 数组?

标签 c# class multidimensional-array reference program-entry-point

在主程序类中我有:

 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.
 }

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

 class AnotherClass
 {
 private string[,,] anotherClassArray;

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

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

我见过一些示例,其中仅将一个简单的一维数组从主程序传递到另一个单独的类并再次返回,但是当我尝试遵循相同的多维示例时,我收到错误:

“尝试初始化新数组时,无法将类型“string[]”隐式转换为“string[,,*]”。

最佳答案

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

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

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

关于c# - 如何从另一个类引用 3D 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37066279/

相关文章:

c++ - 当对象被删除时,复制被删除对象的对象又如何呢?

java - 如何找到 double 变量的 log 2 基数?

php - 过滤递归数组并仅删除 NULL 值

c# - 从程序集中删除强签名

c# - 来自 Windows 窗体控件的控制台输入

c# - 在 F# 中命名元组/匿名类型?

c++ - C++中一个非常简单的枚举类错误

c - 使用数组保存和打印数据时遇到问题

java - 如何显示二维数组的行数和列数?

c# - c#中的递归相关问题