我有三个班级:实体,学生和老师。
所有对象都保存在Entity数组中。
我需要验证Entity[i]
项的类别,但是当我尝试验证时,我会收到警告。程序停止,没有任何进展。怎么办?
class Entity {
string param0;
}
class Student : Entity {
string param1;
//consturctor...
}
class Teacher : Entity {
class string param2;
//consturctor...
}
Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");
...
...
var es = entities[i] as Student;
if (es.param1 != null) //here throw nullReferenceException
Debug.Log(es.param1);
else
Debug.log(es.param2);
我做了什么?我怎样才能正确验证对象类?
答案 0 :(得分:4)
您的问题是您使用不同类型的Entity
设置数组:
Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");
当您尝试将位置1处的实体(即数组中的第二项)强制转换为Student
时,结果将为null
,因为实体为Teacher
:
var es = entities[i] as Student;
es
此时为空。
相反,检查类型,然后在知道实体的类型后访问特定参数。一种方法是:
if (es is Student)
{
Debug.Log((es as Student).param1);
}
else if (es is Teacher)
{
Debug.log((es as Teacher).param2);
}
else
{
//some other entity
}