C# 面向对象基础
本章将介绍面向对象编程(OOP)的基本概念和原则。
面向对象概述
什么是面向对象?
面向对象是一种编程范式,它将程序视为由相互作用的对象组成的系统。每个对象都有自己的状态(属性)和行为(方法)。
面向对象的三大特性
| 特性 | 说明 |
|---|---|
| 封装 | 将数据和对数据的操作封装在一起,隐藏实现细节 |
| 继承 | 新类从已有类获得属性和方法 |
| 多态 | 同一消息可以有不同的响应方式 |
面向对象的五大原则(SOLID)
- Single Responsibility(单一职责):一个类只有一个职责
- Open-Closed(开闭原则):对扩展开放,对修改关闭
- Liskov Substitution(里氏替换):子类可以替换父类
- Interface Segregation(接口隔离):使用多个专门的接口
- Dependency Inversion(依赖倒置):依赖抽象,不依赖具体
类与对象
类的定义
// 定义一个学生类
class Student
{
// 属性(字段)
public string Name;
public int Age;
public string StudentId;
// 构造函数
public Student(string name, int age, string studentId)
{
Name = name;
Age = age;
StudentId = studentId;
}
// 方法
public void Study(string subject)
{
Console.WriteLine($"{Name} 正在学习 {subject}");
}
public void Introduce()
{
Console.WriteLine($"我是 {Name},学号 {StudentId},今年 {Age} 岁");
}
}
创建对象
// 使用构造函数创建对象
Student student = new Student("张三", 20, "S001");
student.Introduce(); // 输出: 我是 张三,学号 S001,今年 20 岁
student.Study("数学");
对象的生命周期
// 创建对象
Student s = new Student("李四", 21, "S002");
// 使用对象
s.Study("物理");
// 对象不再使用,会被垃圾回收器回收
// (开发者无需手动释放内存)
访问修饰符
| 修饰符 | 说明 | 同类 | 子类 | 同一程序集 | 任何地方 |
|---|---|---|---|---|---|
public | 公开 | ✓ | ✓ | ✓ | ✓ |
private | 私有 | ✓ | ✗ | ✗ | ✗ |
protected | 受保护 | ✓ | ✓ | ✗ | ✗ |
internal | 程序集内 | ✓ | ✓ | ✓ | ✗ |
protected internal | 保护或程序集 | ✓ | ✓ | ✓ | ✗ |
private protected | 私有保护(C# 7.2+) | ✓ | ✓ | ✗ | ✗ |
class Person
{
public string Name; // 公开,任何地方可访问
private int _age; // 私有,仅本类可访问
protected string _id; // 受保护,本类和子类可访问
internal string _email; // 程序集内可访问
public void SetAge(int age)
{
if (age >= 0 && age <= 150)
_age = age;
}
}
构造函数
默认构造函数
class Person
{
public string Name;
// 编译器会自动生成默认构造函数
// 如果没有显式定义构造函数
}
// 使用
Person p = new Person(); // 调用默认构造函数
带参数的构造函数
class Person
{
public string Name;
public int Age;
// 带参数的构造函数
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Person p = new Person("张三", 20);
构造函数链
class Person
{
public string Name;
public int Age;
public string City;
// 主构造函数
public Person(string name, int age) : this(name, age, "未知")
{
}
// 完整构造函数
public Person(string name, int age, string city)
{
Name = name;
Age = age;
City = city;
}
}
静态构造函数
class Config
{
public static string AppName;
public static int MaxCount;
// 静态构造函数:类第一次加载时执行一次
static Config()
{
AppName = "MyApp";
MaxCount = 100;
}
}
属性
自动实现属性
class Person
{
// 自动实现属性
public string Name { get; set; }
public int Age { get; set; }
// 只读属性
public string Id { get; }
// 只写属性(不常用)
public string Secret { private get; set; }
}
Person p = new Person();
p.Name = "张三"; // 设置
Console.WriteLine(p.Name); // 读取
自定义 getter 和 setter
class Person
{
private int _age;
public int Age
{
get { return _age; }
set
{
if (value >= 0 && value <= 150)
_age = value;
}
}
// 只读属性示例
public bool IsAdult => Age >= 18;
// 计算属性
public string Info => $"姓名: {Name}, 年龄: {Age}";
}
方法
方法定义
class Calculator
{
// 静态方法
public static int Add(int a, int b)
{
return a + b;
}
// 实例方法
public int Multiply(int a, int b)
{
return a * b;
}
// 返回多个值(元组)
public (int sum, int product) Calculate(int a, int b)
{
return (a + b, a * b);
}
// 可选参数
public void Greet(string name = "Guest")
{
Console.WriteLine($"Hello, {name}!");
}
// 命名参数
public void CreateUser(string name, int age, string city = "北京")
{
Console.WriteLine($"创建用户: {name}, {age}岁, {city}");
}
}
使用示例
Calculator calc = new Calculator();
// 调用实例方法
int result = calc.Multiply(3, 4);
// 调用静态方法
int sum = Calculator.Add(1, 2);
// 使用元组
var (s, p) = calc.Calculate(5, 3);
// 使用命名参数
calc.CreateUser(name: "张三", age: 25);
对象的相等性
引用相等 vs 值相等
class Person
{
public string Name { get; set; }
}
Person p1 = new Person { Name = "张三" };
Person p2 = new Person { Name = "张三" };
Person p3 = p1;
Console.WriteLine(p1 == p2); // False(引用不同)
Console.WriteLine(p1 == p3); // True(同一引用)
重写 Equals 方法
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
if (obj is Person other)
{
return Name == other.Name && Age == other.Age;
}
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Age);
}
}
静态成员
静态字段和属性
class Counter
{
public static int Count { get; private set; }
public Counter()
{
Count++; // 每次创建实例,计数加1
}
public static void Reset()
{
Count = 0;
}
}
Counter c1 = new Counter();
Counter c2 = new Counter();
Console.WriteLine(Counter.Count); // 2
静态类
// 静态类:只包含静态成员,不能实例化
static class MathHelper
{
public const double PI = 3.14159;
public static int Square(int x) => x * x;
public static int Max(params int[] numbers)
{
int max = numbers[0];
foreach (var n in numbers)
if (n > max) max = n;
return max;
}
}
// 使用
int result = MathHelper.Square(5);
小结
- 面向对象概念:封装、继承、多态
- SOLID 原则:五大设计原则
- 类和对象:定义和使用
- 访问修饰符:控制成员可见性
- 构造函数:初始化对象
- 属性:封装字段
- 静态成员:类级别成员
练习
- 创建一个表示矩形的类,包含长、宽属性和计算面积的方法
- 创建一个表示银行的类,使用静态字段跟踪账户数量
- 设计一个学生管理类,封装学生信息的属性
- 实现一个计算器类,重载基本运算符