给 Student 类的 年龄字段 加上验证逻辑 👇
这样可以防止设置非法年龄(比如负数、超过 150 岁等),提高程序的健壮性和安全性。
using System;
public class Student
{
// 👇 私有字段 —— 外部不能直接访问,保证数据安全
private string name;
private int age; // ← 我们要给这个字段加验证!
private string studentId;
private double score;
// 👇 公有属性 —— 控制访问 + 加入验证逻辑
public string Name
{
get { return name; }
set { name = value; }
}
// ✅ 👇 重点:Age 属性中加入年龄验证
public int Age
{
get { return age; }
set
{
if (value < 0)
throw new ArgumentException("年龄不能为负数!");
if (value > 150)
throw new ArgumentException("年龄不能超过150岁!");
age = value; // 验证通过,才赋值
}
}
public string StudentId
{
get { return studentId; }
set { studentId = value; }
}
public double Score
{
get { return score; }
set
{
if (value < 0 || value > 100)
throw new ArgumentException("分数必须在 0~100 之间!");
score = value;
}
}
// 👇 构造函数:初始化时也会触发属性的 set 验证!
public Student(string name, int age, string studentId, double score)
{
Name = name; // 使用属性赋值 → 会触发验证
Age = age; // ← 这里会验证年龄!
StudentId = studentId;
Score = score; // ← 这里也会验证分数!
}
// 👇 行为方法
public void Study()
{
Console.WriteLine($"{Name}({Age}岁)正在努力学习!");
}
// ✅ 带返回值的方法:根据分数返回等级
public string GetGrade()
{
if (Score >= 90) return "A";
else if (Score >= 80) return "B";
else if (Score >= 70) return "C";
else if (Score >= 60) return "D";
else return "F";
}
// ✅ 带返回值的方法:判断是否及格
public bool IsPass()
{
return Score >= 60;
}
}
// ======== 主程序调用 + 测试异常 ========
class Program
{
static void Main()
{
try
{
// ✅ 正常创建对象
Student s1 = new Student("小明", 17, "S1001", 88.5);
s1.Study();
Console.WriteLine($"{s1.Name} 的成绩等级是:{s1.GetGrade()}");
Console.WriteLine($"{s1.Name} 是否及格:{s1.IsPass()}");
Console.WriteLine();
// ❌ 尝试设置非法年龄 —— 会抛出异常!
Student s2 = new Student("小红", -5, "S1002", 92); // ← 年龄为负,会报错!
}
catch (ArgumentException ex)
{
Console.WriteLine($"❌ 创建学生时出错:{ex.Message}");
}
Console.WriteLine();
// ✅ 再试一次合法数据
try
{
Student s3 = new Student("李雷", 16, "S1003", 75);
Console.WriteLine($"{s3.Name}({s3.Age}岁)成绩等级:{s3.GetGrade()}");
}
catch (ArgumentException ex)
{
Console.WriteLine($"❌ 创建学生时出错:{ex.Message}");
}
// ❌ 尝试运行时修改为非法年龄
try
{
Student s4 = new Student("韩梅梅", 18, "S1004", 85);
s4.Age = 200; // ← 运行时修改年龄为 200,会触发验证并抛出异常!
}
catch (ArgumentException ex)
{
Console.WriteLine($"❌ 修改年龄时出错:{ex.Message}");
}
}
}

被折叠的 条评论
为什么被折叠?



