When should you use C# indexers?

后端 未结 10 1625
终归单人心
终归单人心 2020-12-06 10:10

I\'d like to use indexers more, but I\'m not sure when to use them. All I\'ve found online are examples that use classes like MyClass and IndexerClass

10条回答
  •  广开言路
    2020-12-06 10:32

    An indexer use in your situation would be a TeachersClass class, which would encapsulate the students (collection) and the current teacher. Although you could do the same thing by exposing the list of students, but it does show you an example.

    Here is a code example:

    public class TeachersClass
        {
            private List _students;
    
            public TeachersClass(Teacher currentTeacher, List students)
            {
                CurrentTeacher = currentTeacher;
                _students = students;
            }
    
            public Teacher CurrentTeacher { get; set; }
    
            public Student this[int studentID]
            {
                get
                {
                    return (from s in _students
                            where s.Id = studentID
                            select s).First();
                }
            }   
        }
    

提交回复
热议问题