C# 我有一个包含两种类型对象的数组。我需要验证对象类,但是
我有三个班:实体班、学生班和教师班。 所有对象都保存在实体数组中。 我需要验证C# 我有一个包含两种类型对象的数组。我需要验证对象类,但是,c#,c#-4.0,C#,C# 4.0,我有三个班:实体班、学生班和教师班。 所有对象都保存在实体数组中。 我需要验证实体[I]项的类,但当我尝试验证时,我收到一个警告。程序停止,什么也不去。怎么办 class Entity { string param0; } class Student : Entity { string param1; //consturctor... } class Teacher : Entity { class string param2; //consturc
实体[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);
我做什么不直接?如何正确验证对象类?您的问题是您正在使用不同类型的
实体设置数组:
Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");
当您尝试将位置1处的实体(即数组中的第二项)强制转换为学生
,结果将为空
,因为该实体是教师
:
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
}
但是i
从未定义过。。。请提供一个最低限度的工作示例(编译的内容)。“as运算符类似于强制转换操作。但是,如果转换不可行,as将返回null而不是引发异常”-es。在if语句中,param1
应为es