namespace TestOOP
{
using System;
using System.Collections.Generic;
using System.Linq;
internal sealed class Student
{
private string name;
}
internal sealed class Course
{
private ICollection<Student> students;
public ICollection<Student> Students
{
get { return this.students; }
set { this.students = Students; }
}
}
class Program
{
static void Main()
{
var course = new Course();
course.Students.Add(new Student());
Console.WriteLine(course.Students.Count());
}
}
}
그게 내 코드. 그것을 실행할 때 나는 코스에 학생을 추가하려고하는 라인에서 객체의 인스턴스로 설정되지 않은 객체를 얻습니다. 인터페이스를 필드로 사용하는 방법을 설명하는 데 도움이 필요합니다.인터페이스를 필드로 사용하는 방법은 무엇입니까?
internal sealed class Course
{
readonly List<Student> students = new List<Student>();
public ICollection<Student> Students
{
get { return this.students; }
}
}
이것은 Students
속성이 null 결코 있는지 확인합니다, 어떤 코드를 대체 할 수 있습니다 : 수집의 호텔을
특히이 경우 값을 'Students' 속성 (또는 backfield'students')으로 설정하지 않으므로 'null'이고 'Students.Count()'가 throw됩니다. – Sinatr