方法(函数)
类与对象(面向对象基础)
继承与多态
异常处理与调试
[访问修饰符] [static] 返回类型 方法名(参数列表)
{
// 方法体
return 返回值; // 如果返回类型不是 void
}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
}
}可选参数(默认参数)
static void LogMessage(string message, string level = "INFO")
{
Console.WriteLine($"[{level}] {message}");
}
// 调用
LogMessage("系统启动"); // [INFO] 系统启动
LogMessage("错误", "ERROR"); // [ERROR] 错误命名参数
static void RegisterUser(string name, int age, string email = "", bool isActive = true)
{
// 方法体
}
// 调用时可指定参数名
RegisterUser(name: "张三", age: 25);
RegisterUser(age: 30, name: "李四", isActive: false);params 可变参数
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同一方法名,不同参数(数量或类型不同)
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)重载规则:
✅ 参数数量不同
✅ 参数类型不同
❌ 仅返回值不同(编译器无法区分)
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 在这里不可见 ❌
}
}特性 | 静态方法 | 实例方法 |
|---|---|---|
修饰符 |
| 无 |
调用方式 |
|
|
访问实例成员 | ❌ 不能 | ✅ 可以 |
访问静态成员 | ✅ 可以 | ✅ 可以 |
内存分配 | 程序启动时 | 对象创建时 |
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();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; }
}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;
}
}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);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); // 直接通过类名调用修饰符 | 可访问范围 | 说明 |
|---|---|---|
| 任何地方 | 完全公开 |
| 仅当前类内部 | 默认(最严格) |
| 当前类 + 子类 | 继承相关 |
| 当前程序集(项目)内部 | 同项目公开 |
| 当前程序集 + 子类 | 或的关系 |
| 当前程序集内的子类 | 且的关系(C# 7.2+) |
// 类的默认访问修饰符
class DefaultClass { } // 默认 internal
public class PublicClass { } // 显式 public
// 类成员的默认访问修饰符
class Example
{
void Method1() { } // 默认 private
public void Method2() { } // 显式 public
private void Method3() { } // 显式 private
}语法:class 子类 : 父类
// 父类(基类)
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} 汪汪汪!");
}
}关键字 | 用途 |
|---|---|
| 表示继承关系 |
| 访问父类成员 |
| 标记允许子类重写的方法 |
| 重写父类的虚方法 |
| 禁止类继承或方法重写 |
| 抽象类/方法(不能实例化) |
// 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() { } // 子类不能再重写
}// 抽象类(不能实例化)
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;
}
}语法:interface I名称 { 方法签名; }
// 定义接口
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(); // 各自不同实现
}特性 | 抽象类 | 接口 |
|---|---|---|
继承/实现 | 只能继承一个 | 可以实现多个 |
成员 | 字段、属性、方法(有或无实现) | 方法、属性(无实现) |
访问修饰符 | 可以有各种 | 默认 |
构造函数 | 可以有 | 不能有 |
适用场景 | "是什么"(is-a) | "能做什么"(can-do) |
核心:父类引用指向子类对象,调用方法时执行子类的实现。
// 多态示例
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}");
}try
{
// 可能抛出异常的代码
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
// 处理特定异常
Console.WriteLine($"除零错误:{ex.Message}");
}
catch (Exception ex)
{
// 处理所有其他异常
Console.WriteLine($"未知错误:{ex.Message}");
}
finally
{
// 无论是否异常都会执行(释放资源)
Console.WriteLine("执行完毕");
}异常类型 | 触发条件 |
|---|---|
| 除以零 |
| 数组索引越界 |
| 访问 null 对象 |
| 格式转换错误 |
| 参数不合法 |
| 文件不存在 |
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;
}
}// 自定义异常类
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);// 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();
}// ✅ 好的做法
try
{
int result = Divide(a, b);
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"除零错误:{ex.Message}");
throw; // 重新抛出,保留堆栈信息
}
// ❌ 避免的做法
try { /* ... */ }
catch { } // 静默失败,非常危险!
try { /* ... */ }
catch (Exception ex)
{
throw ex; // 丢失堆栈信息(用 throw; 代替)
}快捷键 | 功能 |
|---|---|
F5 | 启动调试 |
F9 | 切换断点 |
F10 | 逐过程(不进入方法内部) |
F11 | 逐语句(进入方法内部) |
Shift+F11 | 跳出当前方法 |
F5(调试中) | 继续运行 |
Ctrl+Shift+F5 | 重启调试 |
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, "年龄不能为负数");class MyClass
{
// 字段
private int _field;
// 属性
public int Property { get; set; }
// 构造函数
public MyClass(int value) { _field = value; }
// 方法
public void Method() { }
// 静态成员
public static void StaticMethod() { }
}// 单继承
class Child : Parent { }
// 调用父类构造
public Child() : base() { }
// 重写方法
public override void VirtualMethod() { }
// 禁止继承
sealed class Final { }// 定义接口
interface IMyInterface
{
void Method();
string Property { get; set; }
}
// 实现接口
class MyClass : IMyInterface
{
public void Method() { }
public string Property { get; set; }
}try { /* 可能出错的代码 */ }
catch (SpecificException ex) { /* 处理特定异常 */ }
catch (Exception ex) { /* 处理所有异常 */ }
finally { /* 释放资源 */ }
// 抛出异常
throw new Exception("错误信息");