Cannot apply indexing with [] to an expression of type `object'

前端 未结 4 1552
梦如初夏
梦如初夏 2021-01-04 04:17

Here is my code: An ArrayList of ArrayList that returns a float:

public ArrayList walls=new ArrayList(); 

public void Start()
{
    walls[0         


        
4条回答
  •  悲&欢浪女
    2021-01-04 05:06

    ArrayList stores objects without limiting what type those objects are. When you access the objects stored in an ArrayList, the compiler doesn't know what type they are, so it just gives you type object.

    You're storing an ArrayList of float in your outer ArrayList. Since you're always storing floats, it would be better to use a List for the inner list, and a List> for the outer list. This way you won't have to type cast from object:

    using System.Collections.Generic;
    
    public List> paredes = new List>();   
    
    
    Start() {
        paredes[0]=RetornaEmList(279,275,0,0,90);
        paredes[1]=RetornaEmList(62,275,0,0,0);
        paredes[2]=RetornaEmList(62,275,62,0,90);
        paredes[3]=RetornaEmList(217,275,62,-62,0);
        paredes[4]=RetornaEmList(62,275,279,0,90);
        paredes[5]=RetornaEmList(41,275,279,0,0);
        paredes[6]=RetornaEmList(279,275,320,0,9);
        paredes[7]=RetornaEmList(320,275,0,-279,0);    
    
    
    
        for (int i=0;i RetornaEmList(float a,float b,float c, float d, float e)
    {
        return new List { a, b, c, d, e };
    }
    

    Since the inner list always has 5 floats, you could also use a float[] instead of a List

    If you just want to make the code work without moving from ArrayList to List, you need an additional cast:

    float a = (float)((ArrayList)paredes[i])[0];
    

    But it's a lot cleaner just to use List instead.

提交回复
热议问题