当前位置:网站首页>C # student management system designed to cope with most examination sites involved in the final period

C # student management system designed to cope with most examination sites involved in the final period

2022-06-10 05:47:00 woyaottk

Design a student management system :

  • Class diagram

 Insert picture description here

  • Knowledge points involved :

    1. Object oriented fundamentals (
      encapsulation :Getter、Setter
      Inherit : An explicit implementation is an interface 、 Implicitly implement the interface 、base、this、 Overloading and rewriting of methods
      polymorphic : Virtual method
    2. A few things like pointers :ref、out、params、delegate
    3. File operations
    4. Several common interfaces :IComparable IComparer
    5. Common data structure :List、Dictionary
    6. Anonymous inner class 、lamba expression 、LINQ
    7. Overload operator
  • Demand analysis :

    1. It can be added, deleted, modified and checked ( Query usage delegation +Lambda+LINQ)
    2. Data persistence ( File operations )
    3. Sorting function to achieve (IComparable IComparer)
  • Harvest :

    1. Getter and Setter Usage of :
      Use methods directly as variables, for example, to student.id assignment student.id = 1 Print student.id Console.WriteLine(student.id)
      Getter、Setter Must immediately follow the variable name

    2. Getter and Setter Will be implemented by default :

      protected int id { get; set; } ===>
      
      public int id
      {
          get
          {
              return this.id;
          }
          set
          {
              id = value;
          }
      }	
      
    3. The rewrite method must add override keyword

      public override string ToString()
      {
          return this.id + " " + this.name + " " + this.age;
      }
      
    4. rewrite Equals Pay attention to the method
      use first as Keyword for type conversion ,as It is safer than forced rotation , If you can't force the transfer back null
      Second, remember to add override
      Last return Judge the condition

    5. C# No, super keyword , The constructor that inherits the parent class uses base

      public Student(int id, string name, int age) : base(id, name, age) { }
      
    6. Operator overloading

      public static Student operator +(Student a, Student b) 
      {
          Student s = new Student();
          s.Id = a.Id + b.Id;
          s.Age = a.Age + b.Age;
          return s;
      }
      
    7. Destructors cannot be used public modification ~StudentManager()

    8. A delegate is actually a function pointer , Usage mode :
      Declare that a function pointer points to a corresponding function

      Select select = DelegateUtils.SelectSample;
      

      Call the function pointed to through this function pointer

      select(students, id);
      
    9. ref and out Equivalent to pointer mark *, But the difference is out Type must be mandatory in a function , Otherwise, it will report a mistake . For example, these two functions :

         public bool Delete(int id, out Student student)
         {
             student = SelectById(id);
             if(student == null)
             {
                 Console.WriteLine(" Check no one ");
                 return false;
             }
             students.Remove(student);
             return true;
         } 
      
         public bool Update(ref Student student, string name, int age)
         {
             student.name = name;
             student.age = age;
             return true;
         }
      
      
    10. File operation usage FileInfo Get information about the file , Use StreamReader and StreamWriter Conduct IO operation

      public void Load()
      {
          string path = @"../../../student.txt";
          FileInfo fileInfo = new FileInfo(path);
          if (!fileInfo.Exists)
              fileInfo.Create().Close();// create a file .Close() Close the stream and release all resources associated with it 
          StreamReader reader = new StreamReader(path);
          while (reader.Peek() != -1)// Determine whether there are characters in the file 
          {
              string str = reader.ReadLine();
              string[] infos = str.Split(" ");
              Student student = new Student(Convert.ToInt32(infos[0]), infos[1], Convert.ToInt32(infos[2]));
              students.Add(student);
          }
          reader.Close();
      }
      
      public void Store()
      {
          string path = @"../../../student.txt";
          FileInfo fileInfo = new FileInfo(path);
          if (!fileInfo.Exists)
              fileInfo.Create().Close();// create a file .Close() Close the stream and release all resources associated with it 
          StreamWriter writer = new StreamWriter(path);
          foreach(Student student in students)
          {
              writer.WriteLine(student.ToString());
              writer.Flush();// Refresh cache 
          }
          writer.Close();
      }
      
    11. Action A delegate is a delegate that has no return value ,<> Can declare the number and type of the incoming parameters

    12. Lambda Expression and Java Just use => To express , and Lambda Expressions can only be used for delegate types

      public static Student SelectLambda(List<Student> students, int id)
      {
          Student ans = null;
          Action<int> action = new Action<int>((int id) => {
              foreach (Student student in students)
              {
                  if (student.id == id)
                  {
                      ans = student;
                      break;
                  }
              }
          });
          action(id);
          return ans;
      }
      
    13. LINQ Similar to database SQL Statements are made up of three parts :
      - Acquisition data source
      - Create a query expression
      - Execute the query

      	var temp = from student in students // Establish result set 
      	                where student.id == id   // Query criteria 
      	                select student;          // Execute the query 
      
  • Source code

using System;
using System.Collections.Generic;
using System.Text;

namespace StudentLib.src
{
    // abstract class     people 
    // In fact, this class doesn't need to be related to inheritance 
    abstract class Person
    {
        //Getter and Setter Immediately following attribute 
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }

        public Person(){}

        public Person(int id, string name, int age)
        {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        // When reloading, pay attention to override keyword 
        public override string ToString()
        {
            return this.id + " " + this.name + " " + this.age;
        }
        public override bool Equals(object obj)
        {
            Person p = obj as Person;
            return this.id == p.id;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace StudentLib.src
{
    // Students 
    // Inheritance uses colons :, Multiple inheritance is separated by commas 
    class Student : Person, IComparable
    {
        public Student() { }

        // Use base Call the constructor of the parent class 
        public Student(int id, string name, int age) : base(id, name, age) { }

        public int CompareTo(object obj)
        {
            Student student = obj as Student;
            return this.id - student.id;
        }

        // Use operator To overload the operator 
        public static Student operator +(Student a, Student b) 
        {
            Student s = new Student();
            s.id = a.id + b.id;
            s.age = a.age + b.age;
            return s;
        }

    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace StudentLib.src
{
    // Student management 
    class StudentManager
    {
        // Declaration delegation 
        public delegate Student Select(List<Student> students, int id);
        // A collection for storing students 
        List<Student> students = new List<Student>();

        // Constructors , Read the initial information of the data from the file when calling the constructor 
        public StudentManager()
        {
            Load();
        }

        // increase 
        public bool Insert(Student student) 
        {
            students.Add(student);
            return true;
        }

        // Delete       Here is to use out So the parameter declares a out
        public bool Delete(int id, out Student student)
        {
            student = SelectById2(id,DelegateUtils.SelectSample);
            if(student == null)
            {
                Console.WriteLine(" Check no one ");
                return false;
            }
            students.Remove(student);
            return true;
        } 
            
        // Change       Here is to use ref So we use a ref
        public bool Update(ref Student student, string name, int age)
        {
            student.name = name;
            student.age = age;
            return true;
        }

        // check       In order to use delegation, the query uses delegation to obtain 
        public Student SelectById(int id)
        {
            
            // Select select = DelegateUtils.SelectSample;
            // Select select = DelegateUtils.SelectLambda;

            Select select = DelegateUtils.SelectLINQ; //  Declare the delegate variable and point to the target function 
            // Call delegate function 
            return select(students, id);
        }

        // check       Here, the delegate is passed in as a parameter 
        public Student SelectById2(int id, Select select)
        {
            // Call delegate function 
            return select(students, id);
        }

        // according to id Sort , It's Jean Student Realization IComparable Of CompareTo Method 
        public void SortById()
        {
            students.Sort();
        }

        // according to age Sort , yes new A comparator is implemented , adopt StudentCompater Realization IComparer Of Compare Method 
        public void SortByAge(IComparer<Student> comparer)
        {
            students.Sort(comparer);
        }

        // Traverse 
        public void Show()
        {
            foreach(Student student in students) 
            {
                Console.WriteLine(student);
            }
        }

        // Load data from file 
        public void Load()
        {
            string path = @"../../../student.txt";
            FileInfo fileInfo = new FileInfo(path);
            if (!fileInfo.Exists)
                fileInfo.Create().Close();// create a file .Close() Close the stream and release all resources associated with it 
            StreamReader reader = new StreamReader(path);
            while (reader.Peek() != -1)// Determine whether there are characters in the file 
            {
                string str = reader.ReadLine();
                string[] infos = str.Split(" ");
                Student student = new Student(Convert.ToInt32(infos[0]), infos[1], Convert.ToInt32(infos[2]));
                students.Add(student);
            }
            reader.Close();
        }

        // Data persistence   Save the data in memory to disk 
        public void Store()
        {
            string path = @"../../../student.txt";
            FileInfo fileInfo = new FileInfo(path);
            if (!fileInfo.Exists)
                fileInfo.Create().Close();// create a file .Close() Close the stream and release all resources associated with it 
            StreamWriter writer = new StreamWriter(path);
            foreach(Student student in students)
            {
                writer.WriteLine(student.ToString());
                writer.Flush();// Refresh cache 
            }
            writer.Close();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;

namespace StudentLib.src
{
    // The comparator 
    class StudentCompater : IComparer<Student>
    {
        public int Compare([AllowNull] Student x, [AllowNull] Student y)
        {
            return x.age - y.age;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StudentLib.src
{
    // Implement the tool class of delegation 
    class DelegateUtils
    {
        // Simple query 
        public static Student SelectSample(List<Student> students, int id)
        {
            foreach (Student student in students)
            {
                if (student.id == id) return student;
            }
            return null;
        }

        // adopt Action and Lambda Expression query 
        public static Student SelectLambda(List<Student> students, int id)
        {
            Student ans = null;
            Action<int> action = new Action<int>((int id) => {
                foreach (Student student in students)
                {
                    if (student.id == id)
                    {
                        ans = student;
                        break;
                    }
                }
            });
            action(id);
            return ans;
        }

        // adopt LINQ Inquire about 
        public static Student SelectLINQ(List<Student> students, int id)
        {
            var temp = from student in students // Establish result set 
                       where student.id == id   // Query criteria 
                       select student;          // Execute the query 

            foreach (Student student1 in temp)
            {
                return student1;
            }

            return null;
        }
    }
}
using System;
using System.Collections.Generic;
using StudentLib.src;

namespace StudentLib
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentManager manager = new StudentManager();

            int bottom = 1;
            while (bottom != 0)
            {
                int index = 0;
                Console.WriteLine("========= Welcome to the student management system ========");
                Console.WriteLine($"{index++}.  Exit the student management system ");
                Console.WriteLine($"{index++}.  Add student ");
                Console.WriteLine($"{index++}.  Delete a student ");
                Console.WriteLine($"{index++}.  Modify a student information ");
                Console.WriteLine($"{index++}.  Query a student's information ");
                Console.WriteLine($"{index++}.  Show student information ");
                Console.WriteLine($"{index++}.  according to id Sort the students' information ");
                Console.WriteLine($"{index++}.  according to age Sort the students' information ");
                Console.WriteLine($"{index++}.  Save student information ");
                Console.WriteLine(" Please enter your instructions ");
                bottom = Convert.ToInt32(Console.ReadLine());
                
                switch (bottom)
                {
                    
                    case 0:
                        Environment.Exit(0);
                        break;
                    case 1:                        
                        manager.Insert(new Student(new Random().Next(), " Zhang San ", new Random().Next()));
                        break;
                    case 2:
                        Console.WriteLine(" Please enter the students you want to delete id");
                        int id = Convert.ToInt32(Console.ReadLine());
                        Student student = new Student();
                        manager.Delete(id, out student);
                        Console.WriteLine(student);
                        break;
                    case 3:
                        Console.WriteLine(" Please enter the student you want to modify id");
                        id = Convert.ToInt32(Console.ReadLine());
                        student = manager.SelectById2(id,DelegateUtils.SelectLambda);
                        Console.WriteLine(" Please enter the name of the student you want to modify ");
                        string name = Console.ReadLine();
                        Console.WriteLine(" Please enter the age of the student to be modified ");
                        int age = Convert.ToInt32(Console.ReadLine());
                        manager.Update(ref student, name, age);
                        Console.WriteLine(student);
                        break;
                    case 4:
                        Console.WriteLine(" Please enter the student to query id");
                        id = Convert.ToInt32(Console.ReadLine());
                        student = manager.SelectById(id);
                        Console.WriteLine(student);
                        break;
                    case 5:                        
                        manager.Show();
                        break;
                    case 6:
                        manager.SortById();
                        break;
                    case 7:
                        manager.SortByAge(new StudentCompater());
                        break;
                    case 8:
                        manager.Store();
                        break;
                }

            }
        }
    }
}
原网站

版权声明
本文为[woyaottk]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100530214693.html