c#比较

类和对象

public class Person
{
    // 字段
    private string name;
    private int age;
    
    // 属性
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    
    // 自动属性
    public int Age { get; set; }
    
    // 构造函数
    public Person(string name, int age)
    {
        this.name = name;
        this.Age = age;
    }
    
    // 方法
    public void Introduce()
    {
        Console.WriteLine($"我叫{name},今年{Age}岁");
    }
}

继承和多态

public class Student : Person
{
    public string StudentId { get; set; }
    
    public Student(string name, int age, string studentId) 
        : base(name, age)
    {
        StudentId = studentId;
    }
    
    // 方法重写
    public override void Introduce()
    {
        Console.WriteLine($"我是学生{Name},学号{StudentId}");
    }
}

异常处理

try
{
    // 可能抛出异常的代码
    int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("除零错误: " + ex.Message);
}
catch (FormatException ex)
{
    Console.WriteLine("格式错误: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("其他错误: " + ex.Message);
}
finally
{
    // 无论是否发生异常都会执行
    Console.WriteLine("清理工作");
}

image
image
image

posted @ 2025-10-09 16:05  Look_Back  阅读(3)  评论(0)    收藏  举报