我通过声明了4个对象数组;
Student[,] s2 =new BSIT[10,4];
s2[studCount,iden] = new BSIT();
Student[,] s3 = new BSCS[10,4];
s3[studCount,iden] = new BSCS();
Student[,] s4 = new MSIT[10,4];
s4[studCount,iden] = new MSIT();
Student[,] s5 = new MSCS[10,4];
s5[studCount,iden] = new MSCS();
然后,我进行了一些大小写转换语句,要求输入类似以下的名称:
case 1://BSIT
{
iden=0;
Console.Write("Enter Name: ");
(s2[studCount,iden]).setName(Console.ReadLine());
do
{
Console.Write("Enter Age(15-30 only): ");
int a = int.Parse(Console.ReadLine());
if(a>=15 && a<=30)
{
(s2[studCount,iden]).setAge(a);
valid=1;
}
else
{
valid=0;
Console.WriteLine("INVALID INPUT. TRY AGAIN.");
}
}
while(valid==0);
}
但是,当我尝试仅在其他其他对象上输入名称时,例如:
case 2://BSCS
{
iden = 1;
Console.Write("Enter Name: ");
(s3[studCount,iden]).setName(Console.ReadLine());
do
{
Console.Write("Enter Age(15-30 only): ");
int a = int.Parse(Console.ReadLine());
if(a>=15 && a<=30)
{
(s3[studCount,iden]).setAge(a);
valid=1;
}
else
{
valid=0;
Console.WriteLine("INVALID INPUT. TRY AGAIN.");
}
}
while(valid==0);
}
它给了我System.NullReferenceException:对象引用未设置为对象的实例。
是的,基类(称为“ Student”)具有所有“名称”设置器和获取器,而派生类BSIT和BSCS都仅从Student类获取“名称”字段。
当我输入BSIT信息,但不输入BSCS,MSIT和MSCS信息时,程序如何正常运行?MSIT和MSCS遵循与BSIT和BSCS完全相同的格式,但是它们仍然不起作用。
问题:
您只需要初始化1个元素
s2[studCount,iden] = new BSIT();
//and so on
0
我想是这样,所以每当您访问索引上的元素时,[studCount,0]
它都可以正常工作。但是没有其他元素。
解决方案:
iden = 1;
Console.Write("Enter Name: ");
s3[studCount,iden] = new BSCS(); //just initialize it before use
(s3[studCount,iden]).setName(Console.ReadLine());
您的方案:
您必须Student
根据他们的保存Discipline
。因此,您生成了一个包含4列(BSIT,BSCS,MSIT,MSCS)的数组,但是却没有像应有的那样使用它们。您用4列创建了4个数组,现在使用您的方法,您的数组最后将在某些位置包含空元素。
您的方法应该是:
您的课程结构是:
Student
BSIT
BSCS
MSIT
MSCS
因此,只需创建一个数组Student
并将不同的子类实例放入其中。
Student[,] students = new Student[10,4]; //index 0 is for BSIT, 1 for BSCS and so on..
我只是在这里为2种情况编写代码,以帮助您了解其工作原理:
case 1://BSIT
{
iden = 0;
Console.Write("Enter Name: ");
//here you'll initialize the object
students[studCount, iden] = new BSIT(); //Student is base, so it can contain all of it's child objects
(students[studCount, iden]).setName(Console.ReadLine());
do
{
Console.Write("Enter Age(15-30 only): ");
int a = int.Parse(Console.ReadLine());
if(a>=15 && a<=30)
{
(students[studCount, iden]).setAge(a);
valid=1;
}
else
{
valid=0;
Console.WriteLine("INVALID INPUT. TRY AGAIN.");
}
}
while(valid==0);
}
case 2://BSCS
{
iden = 1;
Console.Write("Enter Name: ");
(s3[studCount,iden]).setName(Console.ReadLine());
iden = 1;
Console.Write("Enter Name: ");
//here you'll initialize the object
students[studCount, iden] = new BSCS(); //Student is base, so it can contain all of it's child objects (here we're initializing BSCS)
(students[studCount, iden]).setName(Console.ReadLine());
//your code...
现在,什么都不会被覆盖,所有学科都将位于其指定的列。
注意:我已经更改了数组的名称,因此请在您的代码中的任何地方对其进行修复
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句