簡體   English   中英

無法從arraylist中調用我的方法

[英]Cant call my method on object from arraylist

所以我的問題是:我正在嘗試從位於Achievements腳本中的方法printAchiv()中的ArrayList上的Achiv類調用方法getName(),它顯然不起作用。

以下是我在Achievements腳本中獲取此行的錯誤消息: - > Debug.Log(“Achiv”+ i +“:”+ achivList [i] .getName());

類型object' does not contain a definition for getName object' does not contain a definition for ',並且找不到getName' of type對象'的擴展方法getName' of type (您是否缺少using指令或程序集引用?)

我只是想從集合中的obejct訪問var“name”的值。

Achiv類

using UnityEngine;
using System.Collections;

public class Achiv : MonoBehaviour {

        public string name;

        public Achiv(string name )
        {
            this.name= name;
        }

        public string getName()
        {
            return name;
        }
}

成就劇本

    using UnityEngine;
    using System.Collections;

    public class Achievements: MonoBehaviour {

        public  ArrayList achivList = new ArrayList();

        void Start () 
        {
            achivList.Add (new Achiv("First name", "Descirptionn", false));
            achivList.Add (new Achiv("Second name", "Descirptionnn", false));

            printAchiv();
        }

        void printAchiv(){

            for (int i = 0; i <= achivList.Count - 1; i++)
                Debug.Log("Achiv "+i+": "+ achivList[i].getName());
        }   
    }

使用List<Achiv>而不是ArrayList ArrayList是古老的,不再是類型安全的,不應該再使用了。

ArrayList Indexer返回object ,這就是你得到錯誤的原因。 請嘗試以下方法。

public List<Achiv> achivList = new List<Achiv>();

除此之外,

  • 不要公開公開List ,更喜歡ReadOnlyCollectionIEnumerable
  • 除非有充分的理由for否則更喜歡foreach
  • printAchiv沒有遵循正確的命名約定,在c#中我們使用“CamelCase”,將其重命名為PrintAchiv
  • get / set方法適用於不支持屬性的java風格語言。 在c#中,我們使用屬性。 創建一個屬性即Name

ArrayList與Objects一起運行。 您需要將數組索引的結果轉換為Achiv:

(achivList[i] as Achiv).getName()

問題是ArrayList中的元素存儲為object 因此achivList[i]返回一個object ,該object不提供getName()方法。 您可以添加演員:

            Debug.Log("Achiv "+i+": "+ (Achiv)achivList[i].getName());

或者你可以切換到通用列表:

using UnityEngine;
using System.Collections.Generic;

public class Achievements: MonoBehaviour {


    public  List<Achiv> achivList = new List<Achiv>();


    void Start () {

        achivList.Add (new Achiv("First name", "Descirptionn", false));
        achivList.Add (new Achiv("Second name", "Descirptionnn", false));


        printAchiv();

    }


    void printAchiv(){

        for (int i = 0; i <= achivList.Count - 1; i++)
        {

            Debug.Log("Achiv "+i+": "+ achivList[i].getName());
        }
    }   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM