我的arraylist和数组问题? [英] My arraylist and array problem?

查看:90
本文介绍了我的arraylist和数组问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在arraylist中添加许多int[,]数组,但是我无法以int[,]数据类型提取它们.
这段代码将演示我想做什么:

I want to add many int[,] arrays in an arraylist but I couldn''t extract them in int[,] data type.
This code will demonstrate what i want to do:

arraylist Myarraylist =new arraylist();
int [,] array1 = new int[3,2];
int [,] array2 = new int[5,2];
int [,] array3 = new int[6,4];

Myarraylist.add(array1);
Myarraylist.add(array2);
Myarraylist.add(array3);



我希望这个半代码能够发生:



I want this semi-code to happen:

int[,] Myarray1 = Myarraylist[1]



但是当我提取它们时,出现了一个问题,它们甚至不是object[,]
但只是object.如何将它们再次投射到int[,]?

谢谢您的帮助.



but when i extracted them a problem came up that they are objects not even object[,]
but just object. How can I cast them to int[,] again?

Thank you for your help.

推荐答案

您需要转换已取消引用的元素,例如,以下代码将起作用:
You need to cast the dereferenced element, for instance, the following code will work:
ArrayList Myarraylist = new ArrayList();
    int [,] array1 = new int[3,2];
    int [,] array2 = new int[5,2];
    int [,] array3 = new int[6,4];


    Myarraylist.Add(array1);
    Myarraylist.Add(array2);
    Myarraylist.Add(array3);

    // HERE the needed cast
    int[,] Myarray1 = (int[,])Myarraylist[1];

    for (int n = 0; n < 2; n++)
        Console.WriteLine("MyArray1[0,{0}]={1}", n, Myarray1[0, n]);



BTW作为以下注释(来自 MSDN [



BTW as the following note (from MSDN[^]) says

>以2.0版及更高版本的.NET Framework为目标的应用程序应使用System.Collections.Generic命名空间中的通用集合类,与非一般同类产品相比,它们提供了更高的类型安全性和效率.
Applications that target version 2.0 and later of the .NET Framework should use the generic collection classes in the System.Collections.Generic namespace, which provide greater type-safety and efficiency than their non-generic counterparts.



我强烈建议您使用通用容器而不是ArrayList.



I strongly suggest you using generic containers instead of ArrayList.


请勿使用ArrayList;当v.2.0中引入泛型时,它已过时.使用System.Collections.Generic.List.在您的情况下,请使用System.Collections.Generic.List<System.Collections.Generic.List<int>>.

它将代表锯齿状数组.使用System.Collections.Generic.List.ToArray获取等级1的数组.该元素将是列表,将每个与ToArray一起使用以获取嵌套的数组元素.

—SA
Don''t use the ArrayList; it was rendered obsolete when generics were introduced in v.2.0. Use System.Collections.Generic.List. In your case, use System.Collections.Generic.List<System.Collections.Generic.List<int>>.

It will represent jagged array. Use System.Collections.Generic.List.ToArray to get an array of rank 1. The element will be lists, use each one with ToArray to get nested array elements.

—SA


这篇关于我的arraylist和数组问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆