一、基础语法核心
1. 数据类型与变量
// 值类型
int age = 30; // 整型
double pi = 3.14159; // 双精度浮点
decimal price = 99.95m; // 精确小数
bool isActive = true; // 布尔值
DateTime now = DateTime.Now;// 日期时间
// 引用类型
string name = "John Doe"; // 字符串
int[] scores = {
90, 85, 95};// 数组
object obj = new object(); // 基类对象
// 特殊类型
dynamic dynamicVar = "可动态改变类型";
var inferred = "编译器推断类型"; // string
学习重点:
- 值类型与引用类型在内存中的存储差异
- 值类型默认值 vs 引用类型默认值(null)
var
关键字的使用场景与限制dynamic
的动态类型特性与性能影响
2. 程序控制流
// 条件语句
if (temperature > 35) {
Console.WriteLine("高温警告");
}
else if (temperature < 5) {
Console.WriteLine("低温警报");
}
else {
Console.WriteLine("温度正常");
}
// 循环结构
for (int i = 0; i < 10; i++) {
Console.Write(i + " ");
}
List<string> names = new List<string> {
"Alice", "Bob", "Charlie"};
foreach (var name in names) {
Console.WriteLine(name);
}
// Switch模式匹配(C# 8.0+)
string result = data switch {
int i => $"整数: {
i}",
string s => $"字符串: {
s}",
null => "空值",
_ => "未知类型"
};
关键概念:
- 循环中的
break
和continue
使用区别 - Switch表达式与模式匹配的现代用法
- 三元运算符的简洁条件处理
二、面向对象编程核心
1. 类与对象
public class BankAccount {
// 字段
private decimal _balance;
// 属性
public string Owner {
get; set; }
public decimal Balance {
get => _balance;
private set => _balance = value;
}
// 构造函数
public BankAccount(string owner, decimal initialBalance) {
Owner = owner;
_balance = initialBalance;
}
// 方法
public void Deposit(decimal amount) {
if (amount <= 0)
throw new ArgumentException("金额必须大于0");
_balance += amount;
}
public bool Withdraw(decimal amount) {
if (amount <= 0 || amount > _balance)
return false;
_balance -= amount;
return true;
}
}
2. 继承与多态
public class Shape {
public virtual double Area() => 0;
}
public class Circle : Shape {
public double Radius {
get; set; }
public Circle(double radius) => Radius = radius;
public override double Area() => Math.PI * Math.Pow(Radius, 2);
}
public class Rectangle : Shape {
public double Width {
get; set; }
public double Height {
get; set; }
public Rectangle(double width, double height) {
Width = width;
Height = height;
}
public override double Area() => Width * Height;
}
// 使用多态
List<Shape> shapes = new