我有一个包含两种类型对象的数组。我需要验证对象 class 但是
I have an array with two types of object. I need to verify object class but
我有三个 classes:实体、学生和教师。
所有对象都保存在 Entity 数组中。
我需要验证 Entity[i]
项的 class,但是当我尝试验证时,我收到了警告。程序停止,没有任何进展。怎么办?
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);
我做错了什么?我如何才能正确验证对象 class?
您的问题是您正在使用不同类型的 Entity
:
设置数组
Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");
当您尝试将位置 1(即数组中的第二项)的实体转换为 Student
时,结果将是 null
,因为实体是 [=16] =]:
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
}
我有三个 classes:实体、学生和教师。
所有对象都保存在 Entity 数组中。
我需要验证 Entity[i]
项的 class,但是当我尝试验证时,我收到了警告。程序停止,没有任何进展。怎么办?
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);
我做错了什么?我如何才能正确验证对象 class?
您的问题是您正在使用不同类型的 Entity
:
Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");
当您尝试将位置 1(即数组中的第二项)的实体转换为 Student
时,结果将是 null
,因为实体是 [=16] =]:
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
}