C# 基础概念与语言特性

1. C# 语言简介

1.1 什么是 C

C# (读作 “C Sharp”) 是微软开发的一种现代、面向对象的编程语言,于2000年首次发布。C# 是 .NET 平台的主要编程语言之一,具有以下特点:

  • 类型安全:强类型语言,编译时检查类型错误
  • 面向对象:支持封装、继承、多态等OOP特性
  • 内存管理:自动垃圾回收,无需手动管理内存
  • 跨平台:通过 .NET Core/.NET 5+ 支持多平台运行
  • 高性能:编译为中间语言(IL),运行时JIT编译

1.2 C# 的发展历程

版本 发布年份 主要特性
C# 1.0 2002 基础面向对象特性
C# 2.0 2005 泛型、匿名方法、可空类型
C# 3.0 2007 LINQ、Lambda表达式、自动属性
C# 4.0 2010 动态类型、可选参数
C# 5.0 2012 async/await 异步编程
C# 6.0 2015 字符串插值、表达式体成员
C# 7.0 2017 模式匹配、元组、本地函数
C# 8.0 2019 可空引用类型、异步流
C# 9.0 2020 记录类型、顶级程序
C# 10.0 2021 全局using、文件范围命名空间
C# 11.0 2022 原始字符串字面量、泛型特性
C# 12.0 2023 主构造函数、集合表达式

2. .NET 生态系统

2.1 .NET 平台概述

graph TD
    A[.NET 生态系统] --> B[.NET Framework]
    A --> C[.NET Core]
    A --> D[.NET 5+]
    A --> E[Xamarin]
    A --> F[Unity]
    
    B --> B1[Windows 专用]
    B --> B2[完整框架]
    
    C --> C1[跨平台]
    C --> C2[开源]
    
    D --> D1[统一平台]
    D --> D2[现代化]

2.2 .NET 运行时架构

// C# 代码编译和执行流程示例
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

/*
编译流程:
1. C# 源代码 (.cs) → C# 编译器 (csc.exe)
2. 中间语言 (.dll/.exe) → 公共语言运行时 (CLR)
3. 机器代码 → 操作系统执行
*/

3. C# 语言特性

3.1 类型安全

using System;

public class TypeSafetyExample
{
    public static void Main()
    {
        // 强类型检查
        int number = 42;
        string text = "Hello";
        
        // 编译时错误:无法隐式转换
        // number = text; // 错误!
        
        // 显式转换
        string numberAsString = number.ToString();
        
        // 安全转换
        if (int.TryParse("123", out int result))
        {
            Console.WriteLine($"转换成功: {result}");
        }
        
        // 可空类型(C# 2.0+)
        int? nullableInt = null;
        if (nullableInt.HasValue)
        {
            Console.WriteLine($"值: {nullableInt.Value}");
        }
        else
        {
            Console.WriteLine("值为空");
        }
    }
}

3.2 面向对象编程

using System;

// 封装示例
public class BankAccount
{
    private decimal _balance; // 私有字段
    
    // 属性(封装字段访问)
    public string AccountNumber { get; private set; }
    public string Owner { get; set; }
    
    // 只读属性
    public decimal Balance => _balance;
    
    // 构造函数
    public BankAccount(string accountNumber, string owner, decimal initialBalance = 0)
    {
        AccountNumber = accountNumber;
        Owner = owner;
        _balance = initialBalance;
    }
    
    // 方法
    public void Deposit(decimal amount)
    {
        if (amount <= 0)
            throw new ArgumentException("存款金额必须大于0");
            
        _balance += amount;
        Console.WriteLine($"存款 {amount:C},当前余额: {_balance:C}");
    }
    
    public bool Withdraw(decimal amount)
    {
        if (amount <= 0)
            throw new ArgumentException("取款金额必须大于0");
            
        if (amount > _balance)
        {
            Console.WriteLine("余额不足");
            return false;
        }
        
        _balance -= amount;
        Console.WriteLine($"取款 {amount:C},当前余额: {_balance:C}");
        return true;
    }
}

// 继承示例
public class SavingsAccount : BankAccount
{
    public decimal InterestRate { get; set; }
    
    public SavingsAccount(string accountNumber, string owner, decimal interestRate, decimal initialBalance = 0)
        : base(accountNumber, owner, initialBalance)
    {
        InterestRate = interestRate;
    }
    
    // 方法重写
    public virtual void ApplyInterest()
    {
        decimal interest = Balance * InterestRate / 100;
        Deposit(interest);
        Console.WriteLine($"应用利息: {interest:C}");
    }
}

// 使用示例
public class BankingExample
{
    public static void Main()
    {
        var account = new BankAccount("123456", "张三", 1000);
        account.Deposit(500);
        account.Withdraw(200);
        
        var savings = new SavingsAccount("789012", "李四", 2.5m, 5000);
        savings.ApplyInterest();
    }
}

3.3 自动内存管理

using System;
using System.Collections.Generic;

public class MemoryManagementExample
{
    public static void Main()
    {
        // 栈内存 - 值类型
        int stackValue = 42;
        
        // 堆内存 - 引用类型
        string heapValue = "Hello, World!";
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        
        // 垃圾回收示例
        DemonstrateGarbageCollection();
        
        // 手动触发垃圾回收(通常不推荐)
        GC.Collect();
        GC.WaitForPendingFinalizers();
        
        Console.WriteLine("内存管理演示完成");
    }
    
    private static void DemonstrateGarbageCollection()
    {
        // 创建大量对象
        for (int i = 0; i < 1000; i++)
        {
            var tempList = new List<string>();
            for (int j = 0; j < 100; j++)
            {
                tempList.Add($"Item {j}");
            }
            // tempList 在方法结束后变为垃圾,等待回收
        }
        
        // 显示内存使用情况
        long memoryBefore = GC.GetTotalMemory(false);
        Console.WriteLine($"垃圾回收前内存: {memoryBefore / 1024} KB");
        
        GC.Collect();
        
        long memoryAfter = GC.GetTotalMemory(true);
        Console.WriteLine($"垃圾回收后内存: {memoryAfter / 1024} KB");
    }
}

3.4 现代 C# 特性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// C# 9.0 记录类型
public record Person(string FirstName, string LastName, int Age)
{
    public string FullName => $"{FirstName} {LastName}";
}

// C# 10.0 文件范围命名空间
namespace ModernCSharpFeatures;

public class ModernFeaturesDemo
{
    public static async Task Main(string[] args)
    {
        // C# 6.0 字符串插值
        string name = "张三";
        int age = 25;
        Console.WriteLine($"姓名: {name}, 年龄: {age}");
        
        // C# 7.0 元组
        var (min, max) = GetMinMax(new[] { 1, 5, 3, 9, 2 });
        Console.WriteLine($"最小值: {min}, 最大值: {max}");
        
        // C# 8.0 可空引用类型
        string? nullableString = GetNullableString();
        if (nullableString is not null)
        {
            Console.WriteLine($"字符串长度: {nullableString.Length}");
        }
        
        // C# 9.0 记录类型
        var person = new Person("张", "三", 30);
        Console.WriteLine($"完整姓名: {person.FullName}");
        
        // C# 10.0 全局 using(在文件顶部声明)
        // global using System;
        
        // C# 11.0 原始字符串字面量
        string jsonTemplate = """
            {
                "name": "{{name}}",
                "age": {{age}},
                "active": true
            }
            """;
        
        // 异步编程
        await DemonstrateAsyncProgramming();
        
        // LINQ 查询
        DemonstrateLINQ();
    }
    
    // C# 7.0 本地函数
    static (int Min, int Max) GetMinMax(int[] numbers)
    {
        if (numbers.Length == 0)
            throw new ArgumentException("数组不能为空");
            
        int min = numbers[0];
        int max = numbers[0];
        
        foreach (int number in numbers)
        {
            if (number < min) min = number;
            if (number > max) max = number;
        }
        
        return (min, max);
    }
    
    static string? GetNullableString()
    {
        Random random = new Random();
        return random.Next(2) == 0 ? null : "Hello, World!";
    }
    
    static async Task DemonstrateAsyncProgramming()
    {
        Console.WriteLine("开始异步操作...");
        
        // 模拟异步操作
        await Task.Delay(1000);
        
        Console.WriteLine("异步操作完成");
    }
    
    static void DemonstrateLINQ()
    {
        var numbers = Enumerable.Range(1, 10);
        
        // LINQ 查询语法
        var evenNumbers = from n in numbers
                         where n % 2 == 0
                         select n * n;
        
        // LINQ 方法语法
        var oddNumbers = numbers
            .Where(n => n % 2 == 1)
            .Select(n => n * n)
            .ToList();
        
        Console.WriteLine($"偶数平方: {string.Join(", ", evenNumbers)}");
        Console.WriteLine($"奇数平方: {string.Join(", ", oddNumbers)}");
    }
}

4. C# 与其他语言的比较

4.1 C# vs Java

特性 C# Java
平台支持 跨平台(.NET Core+) 跨平台(JVM)
内存管理 垃圾回收 垃圾回收
语法特性 更现代化 相对保守
性能 高性能 高性能
生态系统 .NET生态 Java生态

4.2 C# vs C++

特性 C# C++
内存管理 自动 手动
类型安全 强类型安全 相对较弱
开发效率 中等
性能 最高
学习曲线 平缓 陡峭

5. 实践练习

练习1:基础语法

// 创建一个简单的计算器类
public class Calculator
{
    public double Add(double a, double b) => a + b;
    public double Subtract(double a, double b) => a - b;
    public double Multiply(double a, double b) => a * b;
    public double Divide(double a, double b)
    {
        if (b == 0)
            throw new DivideByZeroException("除数不能为零");
        return a / b;
    }
}

// 使用示例
public class CalculatorTest
{
    public static void Main()
    {
        var calc = new Calculator();
        
        Console.WriteLine($"10 + 5 = {calc.Add(10, 5)}");
        Console.WriteLine($"10 - 5 = {calc.Subtract(10, 5)}");
        Console.WriteLine($"10 * 5 = {calc.Multiply(10, 5)}");
        Console.WriteLine($"10 / 5 = {calc.Divide(10, 5)}");
        
        try
        {
            calc.Divide(10, 0);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine($"错误: {ex.Message}");
        }
    }
}

练习2:面向对象设计

// 设计一个图书管理系统
public abstract class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string ISBN { get; set; }
    public decimal Price { get; set; }
    
    protected Book(string title, string author, string isbn, decimal price)
    {
        Title = title;
        Author = author;
        ISBN = isbn;
        Price = price;
    }
    
    public abstract void DisplayInfo();
}

public class PhysicalBook : Book
{
    public int Pages { get; set; }
    public string Publisher { get; set; }
    
    public PhysicalBook(string title, string author, string isbn, decimal price, int pages, string publisher)
        : base(title, author, isbn, price)
    {
        Pages = pages;
        Publisher = publisher;
    }
    
    public override void DisplayInfo()
    {
        Console.WriteLine($"实体书: {Title} by {Author}");
        Console.WriteLine($"ISBN: {ISBN}, 价格: {Price:C}");
        Console.WriteLine($"页数: {Pages}, 出版社: {Publisher}");
    }
}

public class EBook : Book
{
    public double FileSizeMB { get; set; }
    public string Format { get; set; }
    
    public EBook(string title, string author, string isbn, decimal price, double fileSizeMB, string format)
        : base(title, author, isbn, price)
    {
        FileSizeMB = fileSizeMB;
        Format = format;
    }
    
    public override void DisplayInfo()
    {
        Console.WriteLine($"电子书: {Title} by {Author}");
        Console.WriteLine($"ISBN: {ISBN}, 价格: {Price:C}");
        Console.WriteLine($"文件大小: {FileSizeMB}MB, 格式: {Format}");
    }
}

6. 总结

C# 是一门功能强大、现代化的编程语言,具有以下优势:

  1. 易学易用:语法清晰,开发效率高
  2. 类型安全:编译时检查,减少运行时错误
  3. 丰富的生态系统:庞大的 .NET 生态和第三方库
  4. 跨平台支持:通过 .NET Core/.NET 5+ 支持多平台
  5. 持续演进:定期更新,引入新特性和改进

在下一章中,我们将学习如何搭建 C# 开发环境和配置开发工具。

参考资源