我似乎无法找到修复代码的错误。我得到了一个测试人员课程,并被告知要使正确运行测试人员所需的课程。这是我遇到问题的代码:
测试人员类
using System;
using School;
namespace School
{
class Tester
{
static void Main(string[] args)
{
Faculty scienceFac = University.createFaculty("Science");
}
}
}
教师班级
using System;
namespace School
{
public class Faculty
{
public String faculty;
public Faculty(String faculty)
{
this.faculty = faculty;
}
}
}
大学课程
using System;
namespace School
{
public class University
{
private int numOfFaculties;
public University()
{
numOfFaculties = 0;
}
public void createFaculty(String faculty)
{
numOfFaculties++;
new Faculty(faculty);//?????
}
public int numberOfFaculties()
{
return numOfFaculties;
}
}
}
只有测试人员显示错误,这是我引用命名空间的错误吗?
答案 0 :(得分:0)
除了评论中其他人提到的问题:
大学班级“记住”院系的数量但不“记住”院系本身
您无需将整数字段初始化为0
没有必要使用int numOfFaculties
字段和int numberOfFaculties()
方法 - 这就是属性的用途:public int NumberOfFaculties { get; private set; }
可以很好地完成。
我建议您的University
课程必须是这样的:
public class University
{
private readonly List<Faculty> _faculties = new List<Faculty>();
public List<Faculty> Faculties { get { return _faculties; } }
public Faculty CreateFaculty(string facultyName)
{
var faculty = new Faculty(facultyName);
_faculties.Add(faculty);
return faculty;
}
public int NumberOfFaculties { get { return _faculties.Count; } }
}
CreateFaculty()
创建一个Faculty,将其存储在University
对象内的List中,NumberOfFaculties
计数只是列表的.Count。
因此,要创建一所拥有科学教员的大学,您可以这样称呼:
University uni = new University();
Faculty scienceFac = uni.CreateFaculty("Science");
答案 1 :(得分:-1)
您需要更改createFaculty以返回Faculty的实例。
public Faculty createFaculty(String faculty)
{
numOfFaculties++;
return new Faculty(faculty);
}
您还需要在测试项目中创建一个University实例; createFaculty不是静态的。
static void Main(string[] args)
{
var instance = new University();
var scienceFac = instance.createFaculty("Science");
}