C#灵魂解剖图:从变量囚徒到架构主宰的7层蜕变!

一、基础语法核心

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 => "空值",
    _ => "未知类型"
};

关键概念

  • 循环中的breakcontinue使用区别
  • 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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洁辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值