一、发展历史
C#的主要作者是丹麦计算机科学家安德斯·海尔斯伯格(Anders Hejlsberg),他是该语言的首席设计师,同时也是Turbo Pascal(Pascal 语言编译器)、Delphi(由 Borland(后被 Embarcadero 收购)开发的面向对象编程语言与集成开发环境(IDE))和TypeScript(由微软开发的开源编程语言,JavaScript 的超级版)的创造者,以及.NET框架的创立者。
C#(读作 “C Sharp”)是由微软开发的面向对象编程语言,基于.NET 框架,旨在结合灵活性、性能和生产力。其发展历程如下:
1. 起源与早期版本(2000-2005)
-
2000 年:C# 1.0 随.NET Framework 1.0 发布,设计灵感源自 C++、Java 和 Delphi,目标是简化企业级开发。
-
2005 年:C# 2.0 引入泛型、匿名方法、可空类型和迭代器,增强类型安全和代码复用性。
2. 功能扩展(2007-2010)
-
2007 年:C# 3.0 推出 Lambda 表达式、LINQ(语言集成查询)、自动属性和匿名类型,大幅提升数据查询效率。
-
2010 年:C# 4.0 支持动态类型(
dynamic
)、命名参数、可选参数和 COM 互操作性,增强灵活性。
3. 异步与并行编程(2012-2015)
-
2012 年:C# 5.0 引入
async/await
异步编程模型,简化异步操作的编写。 -
2015 年:C# 6.0 增加异常过滤器、字典初始化语法、空条件运算符(
?.
)和 nameof 表达式,提升代码可读性。
4. 现代特性与跨平台(2017 - 至今)
-
2017 年:C# 7.0 支持模式匹配、元组、局部函数和二进制字面量,增强代码表达力。
-
2019 年:C# 8.0 引入 nullable 引用类型、异步流、范围运算符(
..
)和模式匹配增强,配合.NET Core 实现跨平台开发。 -
2020 年:C# 9.0 推出记录类型(
record
)、顶级程序集、模式匹配改进和 init 只读属性。 -
2022 年:C# 10.0 支持源生成器、文件范围命名空间、集合表达式改进和原始字符串字面量。
-
2023 年:C# 11.0 新增泛型数学、集合切片、原始字符串内插和
required
修饰符,持续优化开发体验。
关键发展背景:
-
随着.NET 从 Windows 平台扩展到.NET Core(2016)和统一的.NET(2020),C# 成为跨平台开发(Windows、macOS、Linux)的核心语言。
-
社区驱动的改进通过.NET 基金会持续推进,例如通过 RFC(Request for Comments)收集开发者反馈。
二、开发工具
C# 开发工具覆盖从 IDE 到命令行,适配不同开发场景:
1. 集成开发环境(IDE)
Visual Studio
Visual Studio Code(VS Code)
JetBrains Rider
工具 | 特点 | 适用场景 |
---|---|---|
Visual Studio | 微软官方全功能 IDE,支持调试、代码分析、UI 设计器,集成.NET 生态工具。 | 企业级应用、Windows 桌面开发 |
Visual Studio Code(VS Code) | 轻量级跨平台编辑器,通过 C# 扩展包支持智能提示、调试和代码重构。 | 跨平台开发、快速原型设计 |
JetBrains Rider | 跨平台 IDE,提供强大的代码分析、重构工具和多语言支持(如 C#、Kotlin)。 | 专业开发者、复杂项目 |
2. 命令行工具
-
.NET CLI:跨平台命令行接口,用于创建项目、编译代码和管理依赖(如
dotnet new
、dotnet build
) -
MSBuild:微软构建平台,通过
.csproj
项目文件定义编译流程,支持自动化构建和 CI/CD
3. 辅助工具
-
Resharper(VS 插件):代码分析、重构建议和代码生成,提升开发效率。
-
NUnit/MSTest/xUnit:单元测试框架,支持自动化测试和断言。
-
Fiddler/Postman:接口调试工具,适用于 C# 开发的 Web 服务测试。
三、基础语法知识
初始化结构
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{internal class Program{static void Main(string[] args){Console.WriteLine("Hello World");}}
}
1. 变量与数据类型
C# 是强类型语言,变量必须先声明后使用,且需指定类型或使用var
隐式推断。
1.1 值类型(Value Types)
直接存储数据值,分配在栈内存中。常见值类型:
int age = 25; // 整数(32位)
double height = 1.75; // 双精度浮点数
bool isStudent = true; // 布尔值
char grade = 'A'; // 字符(Unicode)
decimal salary = 5000.00m; // 高精度小数(金融计算)
特殊值类型:
-
枚举(enum)
:定义命名常量集合:
enum Color { Red, Green, Blue } Color favorite = Color.Blue;
-
结构体(struct)
:轻量级数据结构,可包含字段和方法:
struct Point {public int X;public int Y;public double Distance() => Math.Sqrt(X*X + Y*Y); }
1.2 引用类型(Reference Types)
存储对象引用,实际数据在堆内存中。常见引用类型:
string name = "Doubao"; // 字符串(不可变)
object obj = 42; // 基类型,可引用任何对象
int[] numbers = { 1, 2, 3 }; // 数组
动态类型(dynamic):运行时确定类型(C# 4.0+):
dynamic dynamicVar = "Hello";
dynamicVar = 123; // 合法,运行时绑定
1.3 可空类型(Nullable Types)
处理值类型可能为null
的场景(值类型默认不可为null
):
int? nullableInt = null; // 可空int
if (nullableInt.HasValue) {Console.WriteLine(nullableInt.Value);
} else {Console.WriteLine("Value is null");
}
// 空合并运算符(??)
int result = nullableInt ?? 0; // 若nullableInt为null,赋值0
2. 控制流语句
用于控制程序执行流程,支持常见的条件和循环结构。
2.1 条件语句
// if-else
int score = 85;
if (score >= 90) {Console.WriteLine("优秀");
} else if (score >= 80) {Console.WriteLine("良好");
} else {Console.WriteLine("一般");
}
// switch(支持模式匹配,C# 7.0+)
var day = DayOfWeek.Monday;
switch (day) {case DayOfWeek.Saturday:case DayOfWeek.Sunday:Console.WriteLine("周末");break;default:Console.WriteLine("工作日");break;
}
// switch表达式(C# 8.0+)
string result = day switch {DayOfWeek.Saturday or DayOfWeek.Sunday => "休息",_ => "工作"
};
2.2 循环语句
// for循环
for (int i = 0; i < 5; i++) {Console.WriteLine(i);
}// foreach循环(遍历集合)
var names = new List<string> { "Alice", "Bob" };
foreach (var name in names) {Console.WriteLine(name);
}// while循环
int count = 0;
while (count < 3) {Console.WriteLine(count++);
}// do-while循环(至少执行一次)
do {Console.WriteLine("执行一次");
} while (false);
3. 方法与参数
方法是代码复用的基本单元,支持多种参数传递方式。
3.1 方法定义与调用
// 方法定义(返回类型、方法名、参数列表)
int Add(int a, int b) {return a + b;
}// 调用方法
int sum = Add(3, 5); // sum = 8
3.2 参数传递方式
// 值传递(默认)
void Increment(int value) {value++; // 不影响原始值
}// 引用传递(ref关键字)
void Swap(ref int a, ref int b) {int temp = a;a = b;b = temp;
}
int x = 1, y = 2;
Swap(ref x, ref y); // x=2, y=1// 输出参数(out关键字)
void SplitName(string fullName, out string firstName, out string lastName) {var parts = fullName.Split(' ');firstName = parts[0];lastName = parts.Length > 1 ? parts[1] : "";
}
SplitName("John Doe", out var first, out var last);
3.3 可选参数与命名参数(C# 4.0+)
// 可选参数(提供默认值)
void PrintInfo(string name, int age = 0) {Console.WriteLine($"Name: {name}, Age: {age}");
}
PrintInfo("Alice"); // Age默认0// 命名参数(调用时指定参数名)
PrintInfo(age: 30, name: "Bob");
4. 面向对象基础
C# 是纯面向对象语言,支持封装、继承和多态。
4.1 类与对象
// 类定义
class Person {// 字段(通常私有)private string _name;// 属性(封装字段)public string Name {get => _name;set => _name = value;}// 自动属性(简化写法)public int Age { get; set; }// 构造函数public Person(string name, int age) {Name = name;Age = age;}// 方法public void SayHello() {Console.WriteLine($"Hello, I'm {Name}, {Age} years old.");}
}// 创建对象
var person = new Person("Charlie", 22);
person.SayHello(); // 输出: Hello, I'm Charlie, 22 years old.
4.2 继承与多态
// 基类
class Animal {public virtual void Speak() { // 虚方法,可被子类重写Console.WriteLine("Animal speaks");}
}// 派生类
class Dog : Animal {public override void Speak() { // 重写基类方法Console.WriteLine("Woof!");}
}// 多态调用
Animal animal = new Dog();
animal.Speak(); // 输出: Woof!
4.3 接口(Interface)
定义行为契约,类可实现多个接口:
interface ICanSwim {void Swim();
}interface ICanFly {void Fly();
}class Duck : ICanSwim, ICanFly {public void Swim() => Console.WriteLine("Swimming...");public void Fly() => Console.WriteLine("Flying...");
}
5. 集合与数组
用于存储和操作多个元素。
5.1 数组(Array)
固定长度,类型统一:
int[] numbers = new int[5]; // 声明长度为5的整数数组
numbers[0] = 100;// 初始化器语法
string[] names = { "Alice", "Bob", "Charlie" };// 多维数组
int[,] matrix = new int[3, 3];
5.2 泛型集合(推荐使用)
动态调整大小,类型安全:
// List<T>(动态数组)
var list = new List<int> { 1, 2, 3 };
list.Add(4);
foreach (var num in list) {Console.WriteLine(num);
}// Dictionary<TKey, TValue>(键值对)
var dict = new Dictionary<string, int> {["apple"] = 1,["banana"] = 2
};
Console.WriteLine(dict["apple"]); // 输出: 1// HashSet<T>(不重复集合)
var uniqueNumbers = new HashSet<int> { 1, 2, 2 }; // 实际只有1, 2
6. 异常处理
使用try-catch-finally
结构捕获和处理运行时错误:
try {int result = 10 / 0; // 抛出DivideByZeroException
}
catch (DivideByZeroException ex) {Console.WriteLine("错误:除数不能为零");Console.WriteLine(ex.Message);
}
catch (Exception ex) {Console.WriteLine("未知错误:" + ex.Message);
}
finally {Console.WriteLine("无论是否出错,都会执行此代码");
}
自定义异常:
csharp
public class CustomException : Exception {public CustomException(string message) : base(message) { }
}
7. 命名空间与程序集
-
命名空间(Namespace):组织代码,避免命名冲突:
csharp
namespace MyApp.Data {public class DatabaseConnection { /* ... */ } }// 使用其他命名空间的类型 using MyApp.Data; var conn = new DatabaseConnection();
-
程序集(Assembly):物理打包单元(.dll 或.exe),包含类型和资源。
8. 现代 C# 语法糖(C# 6.0+)
简化代码编写:
// 字符串内插(C# 6.0+)
string name = "Doubao";
Console.WriteLine($"Hello, {name}!"); // 替代string.Format// 表达式体方法(C# 6.0+)
public string GetFullName() => $"{FirstName} {LastName}";// 空条件运算符(C# 6.0+)
string result = person?.Name?.ToUpper(); // 若person或Name为null,直接返回null// 模式匹配(C# 7.0+)
object obj = 42;
if (obj is int num) { // 类型模式匹配并赋值Console.WriteLine(num);
}// 元组(Tuple)(C# 7.0+)
(string First, string Last) GetName() => ("John", "Doe");
var (first, last) = GetName();
通过上述内容,你已了解 C# 的基础语法结构。进一步学习可深入高级特性(如 LINQ、异步编程)或框架应用(如ASP.NET Core)。
四、c#代码框架
C# 代码框架通常指项目的组织结构和基础代码结构,它决定了代码的可维护性、可扩展性和可测试性。以下是常见的 C# 代码框架设计原则和示例:
1.解决方案(Solution)结构
一个完整的 C# 应用通常包含多个项目,按职责划分:
plaintext
MySolution/ ├── src/ # 源代码目录 │ ├── MyApp.Domain/ # 领域模型(实体、值对象、领域服务) │ ├── MyApp.Application/ # 应用服务(业务逻辑) │ ├── MyApp.Infrastructure/ # 基础设施(数据库、文件系统等) │ └── MyApp.WebApi/ # Web API 接口层 └── tests/ # 测试项目├── MyApp.UnitTests/ # 单元测试└── MyApp.IntegrationTests/ # 集成测试
MySolution/
├── src/ # 源代码目录
│ ├── MyApp.Domain/ # 领域模型(实体、值对象、领域服务)
│ ├── MyApp.Application/ # 应用服务(业务逻辑)
│ ├── MyApp.Infrastructure/ # 基础设施(数据库、文件系统等)
│ └── MyApp.WebApi/ # Web API 接口层
└── tests/ # 测试项目├── MyApp.UnitTests/ # 单元测试└── MyApp.IntegrationTests/ # 集成测试
2.项目结构示例
以 ASP.NET Core Web API 项目 为例,典型的项目结构如下:
// MyApp.WebApi (ASP.NET Core Web API)
public class Program
{public static void Main(string[] args){CreateHostBuilder(args).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();});
}public class Startup
{public void ConfigureServices(IServiceCollection services){// 注册服务services.AddControllers();services.AddSwaggerGen();// 依赖注入配置services.AddScoped<IMyService, MyService>();services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){// 配置中间件if (env.IsDevelopment()){app.UseDeveloperExceptionPage();app.UseSwagger();app.UseSwaggerUI();}app.UseRouting();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
}
3.分层架构实现
1. 领域层(Domain)
// MyApp.Domain
public class Product // 实体
{public Guid Id { get; private set; }public string Name { get; private set; }public decimal Price { get; private set; }public Product(string name, decimal price){Id = Guid.NewGuid();Name = name;Price = price;}public void UpdatePrice(decimal newPrice){if (newPrice <= 0) throw new ArgumentException("价格必须大于0");Price = newPrice;}
}public interface IProductRepository // 仓储接口
{Task<Product> GetByIdAsync(Guid id);Task AddAsync(Product product);Task UpdateAsync(Product product);
}
2. 应用层(Application)
// MyApp.Application
public class ProductService : IProductService // 应用服务
{private readonly IProductRepository _repository;public ProductService(IProductRepository repository){_repository = repository;}public async Task<ProductDto> GetProductAsync(Guid id){var product = await _repository.GetByIdAsync(id);if (product == null) throw new NotFoundException("产品不存在");return new ProductDto // 映射到DTO{Id = product.Id,Name = product.Name,Price = product.Price};}public async Task UpdateProductPriceAsync(Guid id, decimal newPrice){var product = await _repository.GetByIdAsync(id);product.UpdatePrice(newPrice);await _repository.UpdateAsync(product);}
}public class ProductDto // 数据传输对象
{public Guid Id { get; set; }public string Name { get; set; }public decimal Price { get; set; }
}
3. 基础设施层(Infrastructure)
// MyApp.Infrastructure
public class EfCoreProductRepository : IProductRepository // EF Core 实现
{private readonly ApplicationDbContext _context;public EfCoreProductRepository(ApplicationDbContext context){_context = context;}public async Task<Product> GetByIdAsync(Guid id){return await _context.Products.FindAsync(id);}public async Task AddAsync(Product product){await _context.Products.AddAsync(product);await _context.SaveChangesAsync();}public async Task UpdateAsync(Product product){_context.Products.Update(product);await _context.SaveChangesAsync();}
}public class ApplicationDbContext : DbContext // 数据库上下文
{public DbSet<Product> Products { get; set; }public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options){}
}
4. 接口层(Web API)
// MyApp.WebApi
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{private readonly IProductService _service;public ProductsController(IProductService service){_service = service;}[HttpGet("{id}")]public async Task<ActionResult<ProductDto>> GetProduct(Guid id){var product = await _service.GetProductAsync(id);return Ok(product);}[HttpPut("{id}/price")]public async Task<IActionResult> UpdateProductPrice(Guid id, [FromBody] decimal newPrice){await _service.UpdateProductPriceAsync(id, newPrice);return NoContent();}
}
4.常用框架组件
-
依赖注入(DI)
// 注册服务 services.AddSingleton<IMySingletonService, MySingletonService>(); services.AddScoped<IMyScopedService, MyScopedService>(); services.AddTransient<IMyTransientService, MyTransientService>();
-
配置管理
// appsettings.json {"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDb"},"AppSettings": {"Timeout": 3000} }// 读取配置 var timeout = Configuration.GetValue<int>("AppSettings:Timeout");
-
日志记录
private readonly ILogger<MyService> _logger;public MyService(ILogger<MyService> logger) {_logger = logger; }public void DoWork() {_logger.LogInformation("工作开始");try{// 业务逻辑}catch (Exception ex){_logger.LogError(ex, "工作失败");throw;} }
-
异步编程
public async Task<IEnumerable<Product>> GetProductsAsync() {return await _context.Products.AsNoTracking().ToListAsync(); }
5.测试框架
// MyApp.UnitTests (xUnit + Moq)
public class ProductServiceTests
{private readonly Mock<IProductRepository> _mockRepository;private readonly ProductService _service;public ProductServiceTests(){_mockRepository = new Mock<IProductRepository>();_service = new ProductService(_mockRepository.Object);}[Fact]public async Task GetProductAsync_ShouldReturnProduct(){// Arrangevar productId = Guid.NewGuid();var mockProduct = new Product("测试产品", 9.99m) { Id = productId };_mockRepository.Setup(r => r.GetByIdAsync(productId)).ReturnsAsync(mockProduct);// Actvar result = await _service.GetProductAsync(productId);// AssertAssert.NotNull(result);Assert.Equal(productId, result.Id);Assert.Equal("测试产品", result.Name);}
}
6.推荐的框架和库
-
Web 开发
-
ASP.NET Core
-
Minimal APIs
-
Blazor (前端框架)
-
-
数据访问
-
Entity Framework Core
-
Dapper
-
MongoDB.Driver
-
-
测试
-
xUnit/NUnit/MSTest
-
Moq
-
FluentAssertions
-
-
工具
-
AutoMapper (对象映射)
-
MediatR (CQRS 模式)
-
Serilog (日志)
-
Polly (弹性和瞬态故障处理)
-
步编程)或框架应用(如ASP.NET Core)。