C# 学习笔记二:方法、类与对象、继承与多态、异常处理与调试

老牛浏览 40评论 0发表于

目录

  1. 方法(函数)

  2. 类与对象(面向对象基础)

  3. 继承与多态

  4. 异常处理与调试

1. 方法(函数)

1.1 方法的基本定义

csharp
[访问修饰符] [static] 返回类型 方法名(参数列表)
{
    // 方法体
    return 返回值;  // 如果返回类型不是 void
}

1.2 方法示例

csharp
class Program
{
    // 无返回值方法
    static void SayHello()
    {
        Console.WriteLine("你好!");
    }
    
    // 有返回值方法
    static int Square(int number)
    {
        return number * number;
    }
    
    // 多个参数
    static int Add(int a, int b)
    {
        return a + b;
    }
    
    static void Main()
    {
        SayHello();                    // 调用无返回值方法
        int result = Square(5);        // result = 25
        int sum = Add(3, 7);           // sum = 10
    }
}

1.3 参数的高级用法

可选参数(默认参数)

csharp
static void LogMessage(string message, string level = "INFO")
{
    Console.WriteLine($"[{level}] {message}");
}

// 调用
LogMessage("系统启动");          // [INFO] 系统启动
LogMessage("错误", "ERROR");     // [ERROR] 错误

命名参数

csharp
static void RegisterUser(string name, int age, string email = "", bool isActive = true)
{
    // 方法体
}

// 调用时可指定参数名
RegisterUser(name: "张三", age: 25);
RegisterUser(age: 30, name: "李四", isActive: false);

params 可变参数

csharp
static int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int n in numbers)
        total += n;
    return total;
}

// 调用
Console.WriteLine(Sum(1, 2, 3, 4, 5));  // 15
Console.WriteLine(Sum(1, 2));           // 3
Console.WriteLine(Sum());               // 0

1.4 方法重载(Overload)

同一方法名,不同参数(数量或类型不同)

csharp
class Calculator
{
    static int Add(int a, int b)
    {
        return a + b;
    }
    
    static int Add(int a, int b, int c)
    {
        return a + b + c;
    }
    
    static double Add(double a, double b)
    {
        return a + b;
    }
    
    static string Add(string a, string b)
    {
        return a + b;
    }
}

// 调用
Add(1, 2);           // 3(重载1)
Add(1, 2, 3);        // 6(重载2)
Add(1.5, 2.7);       // 4.2(重载3)
Add("Hello", " C#"); // "Hello C#"(重载4)

重载规则:

  • ✅ 参数数量不同

  • ✅ 参数类型不同

  • ❌ 仅返回值不同(编译器无法区分)

1.5 作用域(Scope)

csharp
class Program
{
    static int globalCounter = 0;  // 类级变量
    
    static void Method1()
    {
        int localVar = 10;         // 局部变量(只在Method1内)
        globalCounter++;           // ✅ 可访问类级变量
    }
    
    static void Method2()
    {
        int localVar = 20;         // 不同方法可同名(互不影响)
        globalCounter++;           // ✅ 可访问类级变量
    }
    
    static void Main()
    {
        if (true)
        {
            int blockVar = 100;    // 块级作用域
        }
        // blockVar 在这里不可见 ❌
    }
}

1.6 静态方法 vs 实例方法

特性

静态方法

实例方法

修饰符

static

static

调用方式

类名.方法名()

对象.方法名()

访问实例成员

❌ 不能

✅ 可以

访问静态成员

✅ 可以

✅ 可以

内存分配

程序启动时

对象创建时

2. 类与对象(面向对象基础)

2.1 类的基本结构

csharp
class Person
{
    // 字段(存储数据,通常 private)
    private string _name;
    private int _age;
    
    // 属性(控制访问)
    public string Name 
    { 
        get { return _name; }
        set { _name = value; }
    }
    
    // 自动属性(C# 3.0+)
    public string Email { get; set; }
    
    // 只读属性
    public int Age { get; private set; }
    
    // 计算属性
    public string Description => $"{Name}{Age}岁)";
    
    // 构造函数
    public Person(string name, int age)
    {
        _name = name;
        _age = age;
        Age = age;
    }
    
    // 方法
    public void SayHello()
    {
        Console.WriteLine($"你好,我是{Name}");
    }
}

// 使用
Person p = new Person("张三", 25);
p.Name = "张三丰";
p.SayHello();

2.2 属性(Property)的完整写法

csharp
class Student
{
    // 1. 自动属性(最常用)
    public string Name { get; set; }
    
    // 2. 只读属性
    public int Id { get; private set; }
    
    // 3. 带验证的属性
    private int _age;
    public int Age
    {
        get { return _age; }
        set 
        {
            if (value < 0 || value > 150)
                throw new ArgumentException("年龄不合法");
            _age = value;
        }
    }
    
    // 4. 表达式体属性(C# 6.0+)
    public string Info => $"{Name}{Age}岁)";
    
    // 5. 只读属性(仅 get)
    public int Score { get; }
    
    // 6. init-only 属性(C# 9.0+,仅初始化时赋值)
    public string Major { get; init; }
}

2.3 构造函数(Constructor)

csharp
class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Major { get; set; }
    
    // 1. 默认构造函数(无参数)
    public Student()
    {
        Name = "未命名";
        Age = 18;
    }
    
    // 2. 带参数构造函数
    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    // 3. 构造函数链(this 调用另一个构造函数)
    public Student(string name, int age, string major) 
        : this(name, age)  // 先调用上面的构造函数
    {
        Major = major;
    }
}

2.4 this 关键字

csharp
class Person
{
    private string _name;
    private int _age;
    
    public Person(string name, int age)
    {
        this._name = name;   // this 区分参数和字段
        this._age = age;
    }
    
    public Person SetAge(int age)
    {
        this._age = age;
        return this;  // 返回当前对象(支持链式调用)
    }
    
    public void Display()
    {
        Console.WriteLine($"姓名:{this._name},年龄:{this._age}");
    }
}

// 链式调用
Person p = new Person("张三", 25)
            .SetAge(30)
            .SetAge(35);

2.5 静态成员(static)

csharp
class MathUtils
{
    // 静态字段(所有对象共享)
    public static double PI = 3.14159;
    public static int InstanceCount = 0;
    
    // 静态构造函数(自动调用一次)
    static MathUtils()
    {
        PI = Math.PI;
        Console.WriteLine("静态构造函数执行");
    }
    
    // 静态方法
    public static double CircleArea(double radius)
    {
        return PI * radius * radius;
    }
    
    // 实例方法
    public void ShowInfo()
    {
        Console.WriteLine($"PI = {PI}");
    }
}

// 使用
double area = MathUtils.CircleArea(5);  // 直接通过类名调用

2.6 访问修饰符

修饰符

可访问范围

说明

public

任何地方

完全公开

private

仅当前类内部

默认(最严格)

protected

当前类 + 子类

继承相关

internal

当前程序集(项目)内部

同项目公开

protected internal

当前程序集 + 子类

或的关系

private protected

当前程序集内的子类

且的关系(C# 7.2+)

csharp
// 类的默认访问修饰符
class DefaultClass { }        // 默认 internal
public class PublicClass { }  // 显式 public

// 类成员的默认访问修饰符
class Example
{
    void Method1() { }         // 默认 private
    public void Method2() { }  // 显式 public
    private void Method3() { } // 显式 private
}

3. 继承与多态

3.1 继承(Inheritance)

语法:class 子类 : 父类

csharp
// 父类(基类)
class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Animal(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    public void Eat()
    {
        Console.WriteLine($"{Name} 正在吃饭");
    }
    
    public virtual void MakeSound()
    {
        Console.WriteLine($"{Name} 发出声音");
    }
}

// 子类(派生类)
class Dog : Animal
{
    public string Breed { get; set; }
    
    public Dog(string name, int age, string breed) 
        : base(name, age)  // 调用父类构造函数
    {
        Breed = breed;
    }
    
    // 子类特有方法
    public void Bark()
    {
        Console.WriteLine($"{Name} 汪汪!");
    }
    
    // 重写父类方法
    public override void MakeSound()
    {
        Console.WriteLine($"{Name} 汪汪汪!");
    }
}

3.2 继承的关键字

关键字

用途

:

表示继承关系

base

访问父类成员

virtual

标记允许子类重写的方法

override

重写父类的虚方法

sealed

禁止类继承或方法重写

abstract

抽象类/方法(不能实例化)

csharp
// base 的使用
class Car : Vehicle
{
    public Car(string brand) : base(brand) { }
    
    public override void Start()
    {
        base.Start();  // 调用父类方法
        Console.WriteLine("汽车已启动");
    }
}

// sealed 的使用
sealed class FinalClass { }        // 不能被继承

class Parent
{
    public virtual void Method() { }
}

class Child : Parent
{
    public sealed override void Method() { }  // 子类不能再重写
}

3.3 抽象类与抽象方法

csharp
// 抽象类(不能实例化)
abstract class Shape
{
    public string Color { get; set; }
    
    // 抽象方法(无实现,子类必须实现)
    public abstract double CalculateArea();
    
    // 普通方法(有实现)
    public void Display()
    {
        Console.WriteLine($"颜色:{Color},面积:{CalculateArea():F2}");
    }
}

// 子类必须实现抽象方法
class Circle : Shape
{
    public double Radius { get; set; }
    
    public Circle(double radius, string color)
    {
        Radius = radius;
        Color = color;
    }
    
    public override double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

3.4 接口(Interface)

语法:interface I名称 { 方法签名; }

csharp
// 定义接口
interface IFlyable
{
    void Fly();  // 接口方法无实现
}

interface ISwimmable
{
    void Swim();
}

// 类可以实现多个接口
class Duck : IFlyable, ISwimmable
{
    public void Fly()
    {
        Console.WriteLine("鸭子飞");
    }
    
    public void Swim()
    {
        Console.WriteLine("鸭子游泳");
    }
}

// 使用接口多态
List<IFlyable> flyables = new List<IFlyable>();
flyables.Add(new Duck());
flyables.Add(new Airplane());

foreach (IFlyable item in flyables)
{
    item.Fly();  // 各自不同实现
}

3.5 抽象类 vs 接口

特性

抽象类

接口

继承/实现

只能继承一个

可以实现多个

成员

字段、属性、方法(有或无实现)

方法、属性(无实现)

访问修饰符

可以有各种

默认 public

构造函数

可以有

不能有

适用场景

"是什么"(is-a)

"能做什么"(can-do)

3.6 多态(Polymorphism)

核心:父类引用指向子类对象,调用方法时执行子类的实现。

csharp
// 多态示例
List<Shape> shapes = new List<Shape>
{
    new Circle(5, "红色"),
    new Rectangle(4, 6, "蓝色")
};

foreach (Shape shape in shapes)
{
    shape.Display();  // 执行各自子类的实现
}

// 类型检查(is 和 as)
if (shape is Circle circle)
{
    Console.WriteLine($"半径:{circle.Radius}");
}

Circle circle2 = shape as Circle;
if (circle2 != null)
{
    Console.WriteLine($"半径:{circle2.Radius}");
}

4. 异常处理与调试

4.1 try-catch-finally

csharp
try
{
    // 可能抛出异常的代码
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    // 处理特定异常
    Console.WriteLine($"除零错误:{ex.Message}");
}
catch (Exception ex)
{
    // 处理所有其他异常
    Console.WriteLine($"未知错误:{ex.Message}");
}
finally
{
    // 无论是否异常都会执行(释放资源)
    Console.WriteLine("执行完毕");
}

4.2 常用异常类型

异常类型

触发条件

DivideByZeroException

除以零

IndexOutOfRangeException

数组索引越界

NullReferenceException

访问 null 对象

FormatException

格式转换错误

ArgumentException

参数不合法

FileNotFoundException

文件不存在

4.3 抛出异常(throw)

csharp
class BankAccount
{
    private decimal _balance;
    
    public void Withdraw(decimal amount)
    {
        if (amount <= 0)
        {
            throw new ArgumentException("取款金额必须大于0", nameof(amount));
        }
        
        if (amount > _balance)
        {
            throw new InvalidOperationException($"余额不足,当前:{_balance:C}");
        }
        
        _balance -= amount;
    }
}

4.4 自定义异常

csharp
// 自定义异常类
class InsufficientBalanceException : Exception
{
    public decimal CurrentBalance { get; }
    public decimal RequestedAmount { get; }
    
    public InsufficientBalanceException(decimal current, decimal requested)
        : base($"余额不足!当前:{current:C},需要:{requested:C}")
    {
        CurrentBalance = current;
        RequestedAmount = requested;
    }
}

// 使用
throw new InsufficientBalanceException(100m, 150m);

4.5 using 语句(资源释放)

csharp
// using 语句自动调用 Dispose(释放资源)
using (FileStream file = File.OpenRead("data.txt"))
{
    byte[] buffer = new byte[1024];
    file.Read(buffer, 0, buffer.Length);
}  // 自动释放

// 等价于 try-finally
FileStream file2 = null;
try
{
    file2 = File.OpenRead("data.txt");
    // 处理文件
}
finally
{
    file2?.Dispose();
}

4.6 异常处理最佳实践

csharp
// ✅ 好的做法
try
{
    int result = Divide(a, b);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine($"除零错误:{ex.Message}");
    throw;  // 重新抛出,保留堆栈信息
}

// ❌ 避免的做法
try { /* ... */ }
catch { }  // 静默失败,非常危险!

try { /* ... */ }
catch (Exception ex)
{
    throw ex;  // 丢失堆栈信息(用 throw; 代替)
}

4.7 调试快捷键

快捷键

功能

F5

启动调试

F9

切换断点

F10

逐过程(不进入方法内部)

F11

逐语句(进入方法内部)

Shift+F11

跳出当前方法

F5(调试中)

继续运行

Ctrl+Shift+F5

重启调试

4.8 调试输出

csharp
using System.Diagnostics;

// Debug 输出(仅在 Debug 模式下)
Debug.WriteLine("程序开始");
Debug.Indent();
Debug.WriteLine($"变量 x = {x}");
Debug.WriteLineIf(x > 5, "x 大于 5");
Debug.Unindent();

// 断言(条件为 false 时中断)
Debug.Assert(age >= 0, "年龄不能为负数");

📝 快速参考卡片

类定义速查

csharp
class MyClass
{
    // 字段
    private int _field;
    
    // 属性
    public int Property { get; set; }
    
    // 构造函数
    public MyClass(int value) { _field = value; }
    
    // 方法
    public void Method() { }
    
    // 静态成员
    public static void StaticMethod() { }
}

继承速查

csharp
// 单继承
class Child : Parent { }

// 调用父类构造
public Child() : base() { }

// 重写方法
public override void VirtualMethod() { }

// 禁止继承
sealed class Final { }

接口速查

csharp
// 定义接口
interface IMyInterface
{
    void Method();
    string Property { get; set; }
}

// 实现接口
class MyClass : IMyInterface
{
    public void Method() { }
    public string Property { get; set; }
}

异常处理速查

csharp
try { /* 可能出错的代码 */ }
catch (SpecificException ex) { /* 处理特定异常 */ }
catch (Exception ex) { /* 处理所有异常 */ }
finally { /* 释放资源 */ }

// 抛出异常
throw new Exception("错误信息");
点赞
收藏
暂无评论,快来发表评论吧~