好的,所以我正在尝试完成这项任务我得到了一些课程,首先我想制作它们并制作它们的打印功能。后来我需要为组类创建“addStudent”函数,所以我希望我的数组比需要的大。
所以这是我的代码
static void Main(string[] args)
{
Student test = new Student("as", "dsa");
Student test1 = new Student("Stola", "Stolova");
Student test2 = new Student("alo", "maloo");
Student[] students = new Student[5];
students[0] = test;
students[1] = test1;
students[2] = test2;
Group grp = new Group("aklas", students);
grp.print();
Console.Read();
}
//^
//this is my main function
class Student
{
private string firstName;
private string lastName;
public string FirstName
{
get
{
return firstName;
}
}
public Student()
{
firstName = null;
lastName = null;
}
public Student(string nameOne, string nameTwo)
{
firstName = nameOne;
lastName = nameTwo;
}
public void formatPrint()
{
Console.WriteLine("{0,10} {1,10}", firstName, lastName);
}
// ^这是其中一个类
class Group
{
private string name;
private Student[] students;
public Group()
{
name = null;
students = null;
}
public Group(string grpName, Student[] grpStudents)
{
name = grpName;
students = grpStudents;
}
public void print()
{
Console.WriteLine("{0, 15}", name);
for(int i = 0; i < students.Length; i ++)
{
if (students[i].FirstName != null)
students[i].formatPrint();
}
}
}
// ^这是另一个。
所以问题是我为5个元素声明了数组,里面只有3个元素。一切正常,如果我声明数组有3个元素,但如果他们是4或更多我即时获得该空格式,即使我做了if语句。那我的错误在哪里?谢谢!
答案 0 :(得分:2)
您正在调用FirstName
对象的属性null
。这是NullReferenceException
的原因。
您应该检查对象是否为空:
if(students[i] != null)
students[i].formatPrint();
另请查看此问题:What is a NullReferenceException and how do I fix it?
答案 1 :(得分:1)
不要使用use array use genereic List.This会动态增加你的类而不用担心数组的大小。
List<student> cl=new List<student>();
class.add(newstudent);
//to print all students in class use
foreach(Student r in cl)
{
// print info of students
}