在主程序类中我有:
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/