2013-06-25 42 views
0

我发现此代码生成不同类型的二维动态数组,但我如何访问例如:ar [0] - > o [0]?访问不同类型的二维动态数组

Thx!因为你使用的是对象数组

((object[])ar[1])[2] 

获得第二阵列中的第三个对象,但要注意,你必须施放此为正确的类型:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Collections; 
using System.Collections.Generic; 

namespace Collections 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ArrayList ar = new ArrayList(); 
      object[] o = new object[3]; 
      // Add 10 items to arraylist 
      for (int i = 0; i < 10; i++) 
      { 
       // Create some sample data to add to array of objects of different types. 
       Random r = new Random(); 
       o[0] = r.Next(1, 100); 
       o[1] = "a" + r.Next(1,100).ToString(); 
       o[2] = r.Next(1,100); 
       ar.Add(o); 
      } 
     } 
    } 
} 
+0

为什么你甚至想这个代码,你发现了什么? – musefan

回答

3

您可以使用它像这样。

我宁愿推荐这种方法,创建自己的类来保存您的数据。这样你就不需要照顾把对象转换成适当的类型。

public class Randoms 
{ 
    public int Rand1 { get; set; } 
    public string Rand2 { get; set; } 
    public int Rand3 { get; set; } 
} 

,然后使用泛型列表

List<Randoms> = new List<Randoms>(); 

所以在最后的代码是这样的:

List<Randoms> ar = new List<Randoms>(); 
// Add 10 items to list 
for (int i = 0; i < 10; i++) 
{ 
     Randoms rand = new Randoms(); 
     Random r = new Random(); 
     rand.Rand1 = r.Next(1, 100); 
     rand.Rand2 = "a" + r.Next(1, 100).ToString(); 
     rand.Rand3 = r.Next(1, 100); 
     ar.Add(rand); 
}