一、發展歷史
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)。