无法将 [] 索引应用于“对象"类型的表达式 [英] Cannot apply indexing with [] to an expression of type `object'

查看:31
本文介绍了无法将 [] 索引应用于“对象"类型的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

H这是我的代码:返回浮点数的 ArrayList 的 ArrayList:

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

public ArrayList walls=new ArrayList(); 

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

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

ArrayList ReturnInArrayList(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;
}

它给了我以下错误:

错误 CS0021:无法将带有 [] 的索引应用于类型的表达式`对象'

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

我已经完成了选角,有什么问题吗?:(

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

推荐答案

问题是 paredes[i] 返回一个 object ,它是 object 的返回类型code>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];

不过,更好的解决方案是使用泛型并填充 List:

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 };
}

then paredes 是一个 List> 并且您的访问器可以更改为:

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

float a = paredes[i][0];

这篇关于无法将 [] 索引应用于“对象"类型的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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