Как реализовать интерфейс IComparable в индексируемом классе - C#
Формулировка задачи:
Как реализовать интерфейс IComparable, если невозможно доступиться до индексируемых полей внутри самого индексируемого класса.
Листинг программы
- using System;
- using System.Collections;
- using System.Linq;
- using System.Text;
- class Program
- {
- static void Main(string[] args)
- {
- string[] abit = new string[]
- {
- "Udachin", "Nigamaeva","Seregin","Miloradob","Postnikova","Gorobchenko","Moroz","Nosova","Ananiyn","Kulagina","Muhin","Starikova","Borodin"
- };
- Journal journ = new Journal();
- for (int i = 0; i < abit.Length; i++)
- {
- journ[i] = new Student(i + 1, abit[i]);
- }
- foreach (Student st in journ)
- Console.WriteLine(st.Number + " => " + st.Name);
- Console.ReadLine();
- }
- }
- class Student
- {
- int number;
- string name;
- public Student(int number, string name)
- {
- this.number = number;
- this.name = name;
- }
- public int Number
- {
- get { return number; }
- set
- {
- if (value > 0 || value < 31)
- number = value;
- }
- }
- public string Name
- {
- get { return name; }
- set
- {
- if (value.Length > 0 && value.Length < 51)
- name = value;
- }
- }
- }
- class Journal: IEnumerable, IComparable
- {
- ArrayList journal = new ArrayList();
- public Student this[int index]
- {
- get { return (Student)journal[index]; }
- set
- {
- if (index > -1 && (value is Student))
- {
- journal.Add(value);
- }
- }
- }
- public int Length
- {
- get { return journal.Count;}
- }
- public IEnumerator GetEnumerator()
- {
- foreach (object o in journal)
- yield return o;
- }
- public int CompareTo(object input) //???
- {
- return 1;
- }
- }
Решение задачи: «Как реализовать интерфейс IComparable в индексируемом классе»
textual
Листинг программы
- class Student : IComparable<Student>
- {
- int number;
- string name;
- public Student(int number, string name)
- {
- this.number = number;
- this.name = name;
- }
- public int Number
- {
- get { return number; }
- set
- {
- if (value > 0 || value < 31)
- number = value;
- }
- }
- public string Name
- {
- get { return name; }
- set
- {
- if (value.Length > 0 && value.Length < 51)
- name = value;
- }
- }
- public int CompareTo(Student other)
- {
- if ((object)other == null) return 1;
- return string.Compare(this.Name, other.Name);
- }
- }
- class Journal : IEnumerable<Student>
- {
- List<Student> journal = new List<Student>();
- public void Add(Student student)
- {
- journal.Add(student);
- journal.Sort();
- }
- public Student this[int index]
- {
- get { return journal[index]; }
- set { journal[index] = value; }
- }
- public int Length
- {
- get { return journal.Count; }
- }
- public IEnumerator<Student> GetEnumerator()
- {
- return journal.GetEnumerator();
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д