这篇笔记由本地课程资料同步而来,并按博客阅读方式整理。原始课件、教材、作业与数据集仍保存在本地,不随博客发布。返回课程总览

目录

  1. 第一章:C#编程基础与.NET框架
  2. 第二章:C#数据类型与控制结构
  3. 第三章:面向对象编程
  4. 第四章:C#高级特性

第一章 C#编程基础与.NET框架

1.1 C#语言历史

  • 起源: C -> C++ -> Java -> C#
  • 2002年: 微软正式发布C#,主要设计者Anders Hejlsberg
  • 特点: 简洁、现代、面向对象、安全、兼容Web/Mobile

1.2 Microsoft .NET 平台

组件 说明
.NET Framework Windows专用
.NET Core 跨平台
Xamarin 移动应用

1.3 .NET 架构

1
2
3
4
5
C#源文件(.cs)
↓ 编译
中间语言(CIL/MSIL)
↓ JIT编译
本地机器码

1.4 公共语言运行时 (CLR)

  • 执行.NET程序
  • 支持多语言类型系统
  • 内存管理(垃圾回收GC)
  • 线程管理
  • 安全性和异常处理

1.5 应用程序类型

类型 说明
控制台应用 Console.WriteLine/ReadLine
Windows Forms WinForm桌面应用
WPF Windows Presentation Foundation
Web应用 ASP.NET/ASP.NET Core

1.6 基本语法

1
2
3
4
5
6
7
8
9
10
using System;

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string input = Console.ReadLine();
}
}

第二章 C#数据类型与控制结构

2.1 数据类型

值类型 vs 引用类型

值类型 引用类型
int, float, double, bool class, interface, delegate, array
存储在栈中 存储在堆中
直接存储值 存储引用(地址)

基本数据类型

类型 说明 示例
int 32位整数 42
long 64位整数 87L
double 双精度浮点 3.14
bool 布尔值 true/false
char 字符 ‘A’
string 字符串 “Hello”

特殊类型

1
2
3
4
5
6
7
8
// var 推断类型 (C# 3.0+)
var a = 1 + 2;

// nullable 类型 (C# 3.0+)
int? b = 32;

// dynamic 动态类型 (C# 4.0+)
dynamic x = new Cell();

2.2 运算符

算术运算符

1
2
+ - * / %   // 加减乘除取余
++ -- // 自增自减

关系运算符

1
> < >= <= == !=

逻辑运算符

1
2
3
4
5
6
!  // 逻辑非
& // 逻辑与(不短路)
| // 逻辑或(不短路)
&& // 短路与
|| // 短路或
^ // 异或

位运算符

1
& | ^ ~ << >>

2.3 控制结构

if语句

1
2
3
4
if (条件表达式)
语句块;
else
语句块;

switch语句

1
2
3
4
5
6
7
8
9
10
11
12
switch(exp)
{
case const1:
statement1;
break;
case const2:
statement2;
break;
default:
statement_default;
break;
}

for循环

1
2
3
4
for (int i = 1; i <= 100; i++)
{
result += i;
}

while循环

1
2
3
4
5
while (i <= 100)
{
result += i;
i++;
}

do-while循环

1
2
3
4
5
do
{
result += i;
i++;
} while (i <= 100);

foreach循环

1
2
3
4
foreach (int age in ages)
{
// 只读访问,不能修改
}

2.4 跳转语句

语句 说明
break 跳出循环
continue 跳过当前迭代
goto 跳转到标签
return 返回

2.5 数组

一维数组

1
2
int[] a = { 3, 9, 8 };
int[] b = new int[3];

二维数组

1
int[,] matrix = {{1,2,5}, {3,4,0}, {5,6,7}};

交错数组

1
2
3
int[][] t = new int[3][];
t[0] = new int[2];
t[1] = new int[4];

第三章 面向对象编程

3.1 类 (Class)

类的组成

1
2
3
4
5
6
7
8
9
10
11
12
class Person
{
// 字段:表示对象状态
public string name;
public int age;

// 方法:表示对象行为
public void SayHello()
{
Console.WriteLine("Hello! My name is " + name);
}
}

3.2 构造函数

1
2
3
4
5
6
7
8
9
public Person(string n, int a)  // 带参构造
{
name = n;
age = a;
}

public Person() // 无参构造(系统自动生成)
{
}

3.3 this关键字

1
2
3
4
5
6
7
8
9
10
11
public Person(int age, string name)
{
this.age = age; // 区分字段和参数
this.name = name;
}

// 链式构造
public Person() : this(0, "")
{
// 委托给另一个构造
}

3.4 属性 (Property)

1
2
3
4
5
6
7
8
9
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

// C# 3.0+ 简写
public string Name { get; set; }

3.5 索引器 (Indexer)

1
2
3
4
5
6
7
8
9
public class MyList<T>
{
private T[] array;
public T this[int index]
{
get { return array[index]; }
set { array[index] = value; }
}
}

3.6 继承 (Inheritance)

1
2
3
4
5
class Student : Person
{
// 继承父类的字段和方法
// 可以添加新成员或重写
}

3.7 访问修饰符

修饰符 同类 同包 子类 全局
public
protected
internal
protected internal
private

3.8 静态成员 (static)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person
{
static long totalNum; // 所有对象共享

static Person() // 静态构造
{
totalNum = 520000000;
}

static void Print() // 静态方法
{
Console.WriteLine(totalNum);
}
}

3.9 const vs readonly

关键字 初始化 可修改
const 编译时 永不
readonly 运行时 只能一次

3.10 sealed vs abstract

关键字 说明 示例
sealed 不可继承 String, Math
abstract 不可实例化 Array, RandomNumberGenerator

3.11 方法重写 (Override)

1
2
3
4
5
6
7
8
9
10
11
12
13
// new: 隐藏基类方法
// virtual: 基类方法可被重写
// override: 重写基类方法

class Base
{
public virtual void Show() { }
}

class Derived : Base
{
public override void Show() { } // 重写
}

3.12 接口 (Interface)

1
2
3
4
5
6
7
8
9
10
11
public interface IStringList
{
void Add(string s);
int Count { get; }
string this[int index] { get; set; }
}

class MyList : IStringList
{
// 实现接口
}

3.13 结构体 (struct)

1
2
3
4
5
6
7
struct Point
{
public int X;
public int Y;
}

// struct是值类型,class是引用类型

3.14 枚举 (enum)

1
2
3
4
5
6
7
8
enum MyColor
{
Red,
Green = 1,
Blue = 2
}

MyColor c = MyColor.Red;

3.15 简单工厂模式

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
// 抽象产品
abstract class Product
{
public void MethodSame() { }
public abstract void MethodDiff();
}

// 具体产品
class ConcreteProductA : Product
{
public override void MethodDiff() { }
}

// 工厂
class Factory
{
public static Product GetProduct(string arg)
{
if (arg == "A") return new ConcreteProductA();
// ...
}
}

// 客户
Product p = Factory.GetProduct("A");

第四章 C#高级特性

4.1 泛型 (Generic)

泛型类

1
2
3
4
5
6
7
8
9
public class MyArray<T>
{
private T[] array;
public T getItem(int index) { return array[index]; }
public void setItem(int index, T value) { array[index] = value; }
}

MyArray<int> intArray = new MyArray<int>(5);
intArray.setItem(0, 10);

泛型方法

1
2
3
4
5
6
7
8
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}

Swap<int>(ref a, ref b);

4.2 委托 (Delegate)

基本用法

1
2
3
4
delegate double Func(double x);

Func d = new Func(obj.MyMethod);
double result = d(8.9);

Action和Func

1
2
3
4
5
// Action: 返回void的委托
Action<string> print = s => Console.WriteLine(s);

// Func: 有返回值的委托
Func<int, int, int> add = (a, b) => a + b;

多播委托

1
2
3
4
Func multiFun = fun1;
multiFun += fun2; // 添加
multiFun += fun3;
multiFun(1.2); // 调用所有

4.3 事件 (Event)

定义和使用

1
2
3
4
5
6
7
8
9
// 定义委托类型和事件
public delegate void ClickHandler(object sender, EventArgs e);
public event ClickHandler OnClick;

// 触发事件
OnClick?.Invoke(this, e);

// 订阅事件
button.OnClick += new ClickHandler(Btn_OnClick);

示例:闹钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class AlarmClock
{
public event EventHandler<int>? Tick; // 嘀嗒事件
public event EventHandler? Alarm; // 响铃事件

private int currentTime;
private int alarmTime;

public void Run()
{
while (currentTime <= alarmTime)
{
Thread.Sleep(100);
currentTime++;
Tick?.Invoke(this, currentTime);

if (currentTime >= alarmTime)
{
Alarm?.Invoke(this, EventArgs.Empty);
break;
}
}
}
}

4.4 Lambda表达式

1
2
3
4
5
6
7
8
9
10
11
// 完整形式
Func<int, int> square = (int x) => { return x * x; };

// 简写形式
Func<int, int> square = x => x * x;

// 多参数
Func<int, int, int> add = (a, b) => a + b;

// 无参数
Action print = () => Console.WriteLine("Hello");

与集合配合

1
2
3
4
list.ForEach(n => Console.WriteLine(n));

int max = list.Max();
int sum = list.Sum();

4.5 异常处理

基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
try
{
value = 10 / d;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
// 无论是否异常都执行
Console.WriteLine("Finally");
}

常用异常类型

异常 说明
DivideByZeroException 除零
NullReferenceException 空引用
InvalidCastException 类型转换
IndexOutOfRangeException 数组越界
ArgumentException 参数错误

自定义异常

1
2
3
4
5
6
7
class MyException : Exception
{
public MyException(string message) : base(message) { }
}

// 抛出异常
throw new MyException("错误信息");

4.6 命名空间

1
2
3
4
5
6
7
8
namespace xxx.xxxx
{
class MyClass { }
}

// 使用
using xxx.xxxx;
using MyAlias = Namespace.MyClass;

设计模式

简单工厂模式 (Simple Factory Pattern)

意图: 定义一个创建对象的接口,让子类决定实例化哪个类

结构:

1
2
3
客户(Client) → 工厂(Factory) → 产品(Product)

具体产品(ConcreteProduct)

优点:

  • 封装了对象创建细节
  • 客户不需要知道产品类构造函数

缺点:

  • 添加新产品需要修改工厂类
  • 工厂类可能变得臃肿

代码示例:

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
28
// 抽象产品
abstract class Product
{
public abstract void Operation();
}

// 具体产品
class ConcreteProductA : Product
{
public override void Operation() { }
}

// 工厂
class Factory
{
public static Product GetProduct(string type)
{
switch (type)
{
case "A": return new ConcreteProductA();
case "B": return new ConcreteProductB();
default: throw new Exception();
}
}
}

// 使用
Product p = Factory.GetProduct("A");

UML图简介

常用UML图

图类型 用途
类图 展示类及类之间的关系
用例图 从用户角度描述系统功能
时序图 展示对象交互的时间顺序
状态图 描述对象状态及状态转换
活动图 描述业务流程
组件图 展示系统组件及依赖关系
部署图 展示系统硬件结构

常用工具

工具 用途
Visual Studio IDE
LINQPad 轻量级C#测试
ildasm.exe 查看IL中间语言
ILSpy .NET反编译

整理自:软件构造 (C#编程) 课件 01w-04w