【发布时间】:2018-09-24 21:36:54
【问题描述】:
我想知道如何使用类构造函数来设置多维数组的值。我之前使用过构造函数来设置整数的值(见下文),但这种语法似乎不适用于数组。
这是我将如何使用带整数的构造函数
public class Warehouse
{
//declares instance variables
public int radios;
public int televisions;
public int computers;
//Creates constructor with 0 inventory
public Warehouse()
{
radios = 0;
televisions = 0;
computers = 0;
}
上面的这段代码在以前的作业中对我有用。但是,下面的代码是我目前正在尝试修复的。 Visual Studio 表示这些变量未使用,并将保持默认值。此外,为每个索引分配值的行中的逗号带有红色下划线,表示应该使用分号。还有另一种使用构造函数来设置这些数组的值的方法吗?我只想声明这些值以及数组,但赋值要求使用构造函数。
public class Matrix
{
public double[,] matrixX;
public double[,] matrixY;
public double[,] xySum;
public double[,] xyDiff;
public double[,] xScalar;
public Matrix()
{
matrixX = { { 1.1, 2.2, 3.3 }, { 4.4, 5.5, 6.6 }, { 7.7, 8.8, 9.9 } };
matrixY = { { 9.9, 8.8, 7.7 }, { 6.6, 5.5, 4.4 }, { 3.3, 2.2, 1.1 } };
xySum = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
xyDiff = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
xScalar = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
}
【问题讨论】:
-
matrixX = new double[,] { { 1.1, 2.2, 3.3 }, { 4.4, 5.5, 6.6 }, { 7.7, 8.8, 9.9 } }; -
旁注:始终注意 Visual Studio 中的这些红色摆动线。不仅要注意其中的一些,还要注意所有这些。这些红色摆动蛇指示的一些错误只是代码中也有红色摆动蛇的其他错误的副作用。 (哦,有时那些蛇也可以是绿色的...... ;-)
标签: c# arrays multidimensional-array constructor