不能申请用[]索引类型为`对象的前pression“ [英] Cannot apply indexing with [] to an expression of type `object'

查看:180
本文介绍了不能申请用[]索引类型为`对象的前pression“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code:ArrayList的一个ArrayList是返回一个float:

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

public ArrayList paredes=new ArrayList();   

public void Start()
{
    paredes[0] = RetornaEmArrayList(279,275,0,0,90);
    paredes[1] = RetornaEmArrayList(62,275,0,0,0);
    paredes[2] = RetornaEmArrayList(62,275,62,0,90);
    paredes[3] = RetornaEmArrayList(217,275,62,-62,0);
    paredes[4] = RetornaEmArrayList(62,275,279,0,90);
    paredes[5] = RetornaEmArrayList(41,275,279,0,0);
    paredes[6] = RetornaEmArrayList(279,275,320,0,9);
    paredes[7] = RetornaEmArrayList(320,275,0,-279,0);  

    for (int i = 0; i < paredes.Length; i++) {
        float a = (float)paredes[i][0];
        float b = (float)paredes[i][1];
        float c = (float)paredes[i][2];
        float d = (float)paredes[i][3];
        float e = (float)paredes[i][4];
    }
}

ArrayList RetornaEmArrayList(float a,float b,float c, float d, float e)
{
    ArrayList arrayList = new ArrayList();
    arrayList.Add(a);
    arrayList.Add(b);
    arrayList.Add(c);
    arrayList.Add(d);
    arrayList.Add(e);
    return arrayList;
}

它给了我以下错误:

It gives me the following error:

错误CS0021:不能与适用[]索引到类型的前pression
  `对象

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

我已经做了铸造,有什么不好? (

I already did the casting, what is wrong? :(

推荐答案

的问题是,帕雷德斯[I] 返回对象这是的ArrayList 索引器的返回类型。你需要施放此给的ArrayList 才能够访问它:

The problem is that paredes[i] returns an object which is the return type of the ArrayList indexer. You need to cast this to an ArrayList to be able to access it:

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

有一个更好的解决方案,虽然是使用泛型和填充列表与LT;浮动&GT; 而不是:

A better solution though is to use generics and populate a List<float> instead:

List<float> RetornaEmList(float a,float b,float c, float d, float e)
{
    return new List<float> { a, b, c, d, e };
}

然后帕雷德斯列表&LT;名单&LT;浮动&GT;&GT; 和您的访问可以更改为:

then paredes is a List<List<float>> and your accessor can be changed to:

float a = paredes[i][0];

这篇关于不能申请用[]索引类型为`对象的前pression“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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