C# 面向对象 - 类与对象

10.1 类与对象

定义类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Person
{
// 字段
private string _name;
private int _age;

// 属性
public string Name
{
get { return _name; }
set { _name = value; }
}

public int Age
{
get { return _age; }
set { _age = value; }
}
}

创建对象

1
2
3
4
5
6
// 使用 new 创建对象
Person person = new Person();
person.Name = "Alice";
person.Age = 25;

Console.WriteLine($"{person.Name}, {person.Age}岁");

10.2 字段与属性

字段

1
2
3
4
5
6
7
8
9
public class User
{
// 私有字段(通常以下划线开头)
private string _email;
private int _loginCount;

// 公共字段(不推荐)
public string Username;
}

属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Product
{
// 自动属性
public string Name { get; set; }
public decimal Price { get; set; }

// 只读属性
public string Id { get; }

// 带逻辑的属性
private int _stock;
public int Stock
{
get { return _stock; }
set
{
if (value < 0)
throw new ArgumentException("库存不能为负");
_stock = value;
}
}

// 计算属性
public bool IsInStock => Stock > 0;
}

10.3 构造函数

基本构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Student
{
public string Name { get; set; }
public int Age { get; set; }

// 无参构造函数
public Student()
{
Name = "Unknown";
Age = 0;
}

// 带参构造函数
public Student(string name, int age)
{
Name = name;
Age = age;
}
}

// 调用
Student s1 = new Student();
Student s2 = new Student("Alice", 20);

构造函数链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Employee
{
public string Name { get; set; }
public string Department { get; set; }

public Employee(string name) : this(name, "Unassigned")
{
}

public Employee(string name, string department)
{
Name = name;
Department = department;
}
}

10.4 this 关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Point
{
public int X { get; set; }
public int Y { get; set; }

public Point(int x, int y)
{
this.X = x; // this 指代当前实例
this.Y = y;
}

public Point Move(int dx, int dy)
{
this.X += dx;
this.Y += dy;
return this; // 返回当前实例(链式调用)
}
}

10.5 对象初始化器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int Year { get; set; }
}

// 传统方式
Book book1 = new Book();
book1.Title = "C# Guide";
book1.Author = "Microsoft";
book1.Year = 2024;

// 对象初始化器
Book book2 = new Book
{
Title = "C# Guide",
Author = "Microsoft",
Year = 2024
};

// 调用构造函数后初始化
Book book3 = new Book("C# Guide")
{
Author = "Microsoft",
Year = 2024
};

10.6 静态成员

静态字段与属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Counter
{
// 静态字段(所有实例共享)
private static int _totalCount = 0;

// 静态属性
public static int TotalCount => _totalCount;

public Counter()
{
_totalCount++;
}
}

// 使用
var c1 = new Counter();
var c2 = new Counter();
Console.WriteLine(Counter.TotalCount); // 2

静态方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MathHelper
{
public static double Pi => 3.14159265358979;

public static int Max(int a, int b)
{
return a > b ? a : b;
}

public static double CircleArea(double radius)
{
return Pi * radius * radius;
}
}

// 调用(无需创建实例)
Console.WriteLine(MathHelper.Max(10, 20)); // 20
Console.WriteLine(MathHelper.CircleArea(5));

静态类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static class StringHelper
{
public static bool IsNullOrEmpty(string s)
{
return string.IsNullOrEmpty(s);
}

public static string Reverse(string s)
{
char[] chars = s.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
}

// 静态类不能实例化
// var helper = new StringHelper(); // 错误

10.7 访问修饰符

修饰符 说明
public 任何代码都可访问
private 仅类内部可访问
protected 类和派生类可访问
internal 同一程序集可访问
protected internal 同一程序集或派生类
private protected 同一程序集的派生类

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class BankAccount
{
// 私有字段
private decimal _balance;

// 公共属性(只读)
public decimal Balance => _balance;

// 公共方法
public void Deposit(decimal amount)
{
if (amount > 0)
_balance += amount;
}

// 私有方法
private bool CanWithdraw(decimal amount)
{
return amount <= _balance;
}
}

10.8 只读字段与常量

readonly 字段

1
2
3
4
5
6
7
8
9
10
public class Config
{
// 运行时常量
public readonly string ConnectionString;

public Config(string connectionString)
{
ConnectionString = connectionString; // 只能在构造函数赋值
}
}

const 常量

1
2
3
4
5
6
7
public class Constants
{
// 编译时常量
public const double Pi = 3.14159265358979;
public const int MaxSize = 100;
public const string AppName = "MyApp";
}

10.9 析构函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Resource
{
~Resource()
{
// 清理非托管资源
Console.WriteLine("资源已释放");
}
}

// 推荐使用 IDisposable 模式
public class FileHandler : IDisposable
{
private FileStream _stream;

public void Dispose()
{
_stream?.Dispose();
}
}

// 使用 using 自动释放
using (var handler = new FileHandler())
{
// 使用资源
} // 自动调用 Dispose

10.10 本章小结

  • 类是对象的模板,对象是类的实例
  • 字段存储数据,属性提供访问控制
  • 构造函数初始化对象,支持重载和链式调用
  • this 指代当前实例
  • 对象初始化器简化对象创建
  • 静态成员属于类,不属于实例
  • 访问修饰符控制可见性
  • readonly 运行时常量,const 编译时常量

练习题

  1. 创建 Rectangle 类,计算面积和周长
  2. 实现 BankAccount 类,支持存款、取款、查询余额
  3. 使用静态方法实现温度转换(摄氏/华氏)
  4. 以下代码输出什么?
    1
    2
    3
    4
    class Test { public static int Count = 0; public Test() { Count++; } }
    var t1 = new Test();
    var t2 = new Test();
    Console.WriteLine(Test.Count);
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
分享: