[英]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
getNameobject' 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
,更喜歡ReadOnlyCollection
或IEnumerable
。 for
否則更喜歡foreach
。 printAchiv
沒有遵循正確的命名約定,在c#中我們使用“CamelCase”,將其重命名為PrintAchiv
。 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.