首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 學生類 Student 繼承 Person 完整實作範例

     編輯:程式設計綜合問答

需求分析

定義 Student 類別繼承 Person,包含學號、課程成績集合、學生身份枚舉、唯讀屬性課程門數、重載方法新增課程。

核心程式碼實作

1. 基礎枚舉與結構體

public enum SexType { Male, Female, Unknown }
public enum ProTitle { Assistant, Lecturer, AssociateProfessor, Professor, Unknown }
public enum StuTitle { Monitor, ViceMonitor, StudyCommittee, Member }

public struct CourseScore {
    public string CourseName;
    public float Score;
}

2. 抽象基類 Person

public abstract class Person {
    // 欄位
    protected string name;
    protected float height;
    protected float weight;
    protected SexType sex;
    protected string id; // 身分證號

    // 屬性
    public string Name { get => name; set => name = value; }
    public float Height { get => height; set => height = value; }
    public float Weight { get => weight; set => weight = value; }
    public SexType Sex { get => sex; set => sex = value; }
    public string ID { 
        get => id; 
        set {
            if (value.Length == 18 && !value.Contains(" "))
                id = value;
            else
                throw new ArgumentException("身分證號必須 18 碼且無空格");
        }
    }
    public int Age { get; } // 唯讀,實作略

    // 建構函式
    public Person() {
        name = "Unknown";
        height = 0;
        weight = 0;
        sex = SexType.Unknown;
        ID = "999999999999999999";
    }
    public Person(string name, string id, float height, float weight, SexType sex) {
        this.name = name;
        this.height = height;
        this.weight = weight;
        this.sex = sex;
        this.ID = id;
    }

    // 抽象方法
    public abstract void Saying();
    public abstract void Write(FileStream fs);
    public abstract void Read(FileStream fs);
}

3. Student 類別完整實作

public class Student : Person {
    // 欄位
    private string stuID;
    private List<CourseScore> courseScores = new List<CourseScore>();
    private StuTitle title;

    // 屬性
    public string StuID { 
        get => stuID; 
        set => stuID = value; // 實際可加長度驗證
    }
    public StuTitle Title { get => title; set => title = value; }
    public int CourseNumber => courseScores.Count; // 唯讀屬性

    // 建構函式
    public Student() : base() { }
    public Student(string name, string id, float height, float weight, SexType sex, string stuID, StuTitle title)
        : base(name, id, height, weight, sex) {
        this.stuID = stuID;
        this.title = title;
    }

    // 重載方法:新增課程
    public void CourseAdd(string courseName, float score) {
        CourseScore cs = new CourseScore { CourseName = courseName, Score = score };
        courseScores.Add(cs);
    }
    public void CourseAdd(CourseScore course) {
        courseScores.Add(course);
    }

    // 取得最高、最低、平均分
    public void GetScore(ref double highScore, ref double lowScore, ref double avgScore) {
        if (courseScores.Count == 0) {
            highScore = lowScore = avgScore = 0;
            return;
        }
        highScore = courseScores.Max(c => c.Score);
        lowScore = courseScores.Min(c => c.Score);
        avgScore = courseScores.Average(c => c.Score);
    }

    // 覆寫抽象方法
    public override void Saying() {
        Console.WriteLine("我正在上課,不方便接電話");
    }
    public override void Write(FileStream fs) { /* 序列化實作 */ }
    public override void Read(FileStream fs) { /* 反序列化實作 */ }

    // 覆寫 ToString
    public override string ToString() {
        return $"學生: {Name}, 學號: {StuID}, 身份: {Title}, 課程數: {CourseNumber}";
    }
}

關鍵點解析

  1. 封裝性:courseScores 設為 private,對外暴露唯讀屬性 CourseNumber 與新增方法。
  2. 重載:兩個 CourseAdd 參數列表不同,滿足「字串+分數」與「結構體」兩種呼叫方式。
  3. 繼承鏈:透過 base() 呼叫父類建構函式,確保基礎欄位正確初始化。
  4. 結構體 vs 類別:CourseScore 用 struct 輕量級,避免堆積分配開銷。

測試範例

var stu = new Student("小明", "110101200001011234", 1.75f, 65f, SexType.Male, "2023001", StuTitle.Monitor);
stu.CourseAdd("數學", 92.5f);
stu.CourseAdd("英文", 88.0f);
stu.CourseAdd(new CourseScore { CourseName = "程式設計", Score = 95.5f });

double high = 0, low = 0, avg = 0;
stu.GetScore(ref high, ref low, ref avg);
Console.WriteLine($"最高:{high}, 最低:{low}, 平均:{avg}");

此設計符合單一職責、開放封閉原則,易於擴展(如加入排名、學分計算等)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved