简体   繁体   中英

Two dimensional C# Array initialized with 2 other arrays

I'm a bit new to C# and I don't understand how to make this work:

private static readonly Unit[,] UNIT_TYPES = new Unit[,]{LENGTH_UNITS, ANGLE_UNITS};
private static readonly Unit[] LENGTH_UNITS = new Unit[3]{Unit.Millimeters, Unit.Inches, Unit.Centimeters};
private static readonly Unit[] ANGLE_UNITS = new Unit[2]{Unit.Degrees, Unit.Radians};

I'm getting the error "A nested array initializer was expected" on the UNIT_TYPES variable. It seems to not except the fact that LENGTH_UNITS and ANGLE_UNITS will be ready at compile time. What's the best way to rewrite this?

Thanks!

You're trying to initialize a rectangular array - whereas what you're providing would be more suitable as a jagged array. A rectangular array is a single array with multiple dimensions - whereas a jagged array is an array of arrays - ie it's a single-dimensional array whose element type is another array type (so each element is an array reference).

You should fix the initialization order too, otherwise you'll just have null entries (because the jagged array would be initialized with the current values of the other variables, which will be null until initialized...)

private static readonly Unit[] LengthUnits = { Unit.Millimeters, Unit.Inches, Unit.Centimeters };
private static readonly Unit[] AngleUnits = { Unit.Degrees, Unit.Radians };
private static readonly Unit[][] UnitTypes = { LengthUnits, AngleUnits };

问题是,您正在做的是创建一个数组数组,但是编译器希望使用二维数组。

You're trying to initialize a rectangular array

int[,] Position = { {2 , 3}, {4 , 5}, {6 , 7} };

this like three array inside a array Eq:

     int[] IN0 = { 2, 3 };
     int[] IN1 = { 4, 5 };
     int[] IN2 = { 6, 7 };``

     int[][] Final = { IN0, IN1, IN2 };

int[,] = the way of create Rect some as grids. int[][] = the way of accessing grid or 2d images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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