简体   繁体   English

C# int 和array 的锯齿状数组

[英]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.它必须是 Int 和 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它必须是 Int 和 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

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 .这样做的问题显然是您在稍后访问它们时需要知道每个数组条目的类型,因为它们都被声明为object

Look at this:看这个:

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

items at index 0, 1, 2 are integers.索引 0、1、2 处的项目是整数。 item at index 4 is another type like this:索引 4 处的项目是另一种类型,如下所示:

{ 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 .因此,您可以保留上述所有内容的唯一数组类型将是object类型的数组,因为 .NET 中的所有内容都源自object

Like this:像这样:

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

Or you an use ArrayList :或者你使用ArrayList

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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