简体   繁体   中英

C# jagged array of int and array

I can't find out how to do the following array:

{ 3, 5, 15, { 4, 75, { 25 } } }

It must be mix of Int and Array. My code for the function is as follows:

p.myMethod(new int[]{ 3, 5, 15, new int[] { 4, 75, new int []{ 25 } } })

But it doesn't work. How can I get my expected result?

It must be mix of Int and Array

The only way to have an array contain multiple types of objects would be to declare and initialize the arrays with the type of a base class of all of the elements, so in this case you would have to use object :

object[] array = new object[]{ 3, 5, 15, new object[] { 4, 75, new object []{ 25 } } };

The problem with this is obviously that you'll need to know the type of each array entry when accessing them later on because they are all declared as object .

Look at this:

{ 3, 5, 15, { 4, 75, { 25 } } }

items at index 0, 1, 2 are integers. item at index 4 is another type like this:

{ 4, 75, { 25 } }

Arrays cannot have multiple types in them. When you create an array you have to specify the type it will contain.

Therefore, the only array type you can keep all of the above will be an array of type object since everything in .NET derive from object .

Like this:

var a = new object[] { 3, 5, 15, new object[] { 4, 75, new[] { 25 } } };

Or you an use ArrayList :

var a = new ArrayList { 3, 5, 15, new ArrayList() { 4, 75, new ArrayList() { 25 } } };

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