【问题标题】:Error CS1061 - List<T>.Item[Int32] Property错误 CS1061 - List<T>.Item[Int32] 属性
【发布时间】:2018-07-07 04:09:41
【问题描述】:

这个问题与this questionthis questionthis question(相同的错误,不同的源类)和this question(相同的错误,不同的原因)非常相似。

在项目中编译我的程序以检查错误后,我收到以下 CS1061 错误:

Entity.cs(291,24): 错误 CS1061: 'List&lt;Entity&gt;' 不包含 'Item' 的定义并且没有扩展方法 'Item' 接受第一个 可以找到类型为“List&lt;Entity&gt;”的参数(您是否缺少 使用指令还是程序集引用?)

Entity.cs是发生错误的文件名,该错误发生在Load()函数中,如下图:

public void Load(){
    /*
        Try to spawn the entity.
        If there are too many entities
        on-screen, unload any special
        effect entities.
        If that fails, produce an error message
    */
    try{
        if(EntitiesArray.Count >= EntitiesOnScreenCap){
            if(this.Type == EntityType.SpecialEffect)
                Unload();
            else
                throw null;
        }else
            //Place the entity in the first available slot in the array
            for(int i = 0; i < EntitiesArray.Capacity; i++)
                if(EntitiesArray.Item[i] == NullEntity)
                    EntitiesArray.Item[i] = this;
    }catch(Exception exc){
        throw new LoadException("Failed to load entity.");
    }
}

错误发生在这些行(第 291 和 292 行):

if(EntitiesArray.Item[i] == NullEntity)
    EntitiesArray.Item[i] = this;

NullEntityEntity 类型的字段,this 也是 Entity 类型的字段。

EntitesArray 是一个 List&lt;Entity&gt;,因此,根据 MSDN 文档 here,应该有一个 Item[] 属性。
Entity 没有名为 Item 的方法或数组。

开课声明Entity:

public static List<Entity> EntitiesArray;

Entity 中保证只运行一次的方法中的实例化:

EntitiesArray = new List<Entity>(EntitiesOnScreenCap);

字段 EntitiesOnScreenCap 是一个等于 200 的 int

这包含在最高范围内(在命名空间之前),因此对此应该没有任何问题:

using System.Collections.Generic;

是什么导致了这个 CS1061 错误,我该如何解决?

【问题讨论】:

    标签: c# compiler-errors generic-list


    【解决方案1】:

    Item 属性不是 C# 中的普通属性。这是一种指示您可以使用索引器从 Enumerable 中引用特定项目的方法。要使用它,只需将索引器值放在方括号内:

    EntitiesArray[i]
    

    【讨论】:

    • 哦,在这方面就像使用常规数组一样。
    • 语法是一样的,在List的情况下,是的,基本上是一样的。但是,可能有非整数索引器,它们甚至可能被重载。例如,NameValueCollection 同时具有 int 和字符串索引器。因此,您可以按位置或名称引用项目。例如,nvc[0]nvc["FirstName"] 都对名为 nvcNameValueCollection 有效。
    猜你喜欢
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多