news 2026/2/7 15:13:30

C# 從入門到精通:全方位掌握現代程式語言

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C# 從入門到精通:全方位掌握現代程式語言

C# 從入門到精通:全方位掌握現代程式語言

第一部分:C# 入門基礎

1.1 C# 概述與發展歷程

C#(發音為 "C Sharp")是由微軟在 2000 年推出的現代化、物件導向的程式語言。它結合了 C++ 的強大功能與 Java 的簡潔性,並在 .NET 框架上執行。隨著時間推移,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-9.0 (2015-2020):語法糖、模式匹配、記錄類型等

  • C# 10.0-12.0 (2021-2023):全局 using、文件級命名空間等

1.2 開發環境設定

Visual Studio 安裝與設定:

bash

# 使用 Visual Studio Installer 安裝 # 選擇工作負載: # - .NET 桌面開發 # - ASP.NET 和網頁開發 # - 通用 Windows 平台開發 # - 移動應用開發

或使用 VS Code:

bash

# 安裝必要擴充功能 # - C# for Visual Studio Code # - .NET Core Debugger # - NuGet Package Manager

.NET CLI 基本指令:

bash

dotnet --version # 檢查版本 dotnet new console -n MyApp # 建立新控制台專案 dotnet build # 編譯專案 dotnet run # 執行專案 dotnet add package Newtonsoft.Json # 添加 NuGet 套件

1.3 基礎語法與資料類型

基本資料類型:

csharp

// 數值類型 byte age = 25; // 8位元無符號 (0-255) short temperature = -10; // 16位元有符號 int population = 1400000000; // 32位元有符號 (最常用) long bigNumber = 9000000000L; // 64位元有符號 float pi = 3.14f; // 32位元浮點數 double precise = 3.14159265358979; // 64位元浮點數 decimal money = 9999.99m; // 128位元精確十進制 (金融計算) // 布林與字符 bool isActive = true; // 布林值 char grade = 'A'; // 16位元 Unicode 字符 // 字串 string name = "John Doe"; // Unicode 字串

變數與常數:

csharp

// 變數宣告 var message = "Hello"; // 隱式類型 (編譯時推斷) dynamic data = GetData(); // 動態類型 (執行時解析) // 常數 const double PI = 3.14159; const int MAX_USERS = 100; // 唯讀變數 (執行時賦值) readonly DateTime createdDate = DateTime.Now;

1.4 運算子與表達式

算術運算子:

csharp

int a = 10, b = 3; int sum = a + b; // 13 int difference = a - b; // 7 int product = a * b; // 30 int quotient = a / b; // 3 (整數除法) float realQuotient = a / (float)b; // 3.333... int remainder = a % b; // 1 // 遞增/遞減 int x = 5; int y = ++x; // x=6, y=6 (前置) int z = x++; // z=6, x=7 (後置)

比較與邏輯運算子:

csharp

bool isEqual = (5 == 5); // true bool notEqual = (5 != 3); // true bool greater = (10 > 5); // true bool logicalAnd = (true && false); // false bool logicalOr = (true || false); // true bool logicalNot = !true; // false // 三元運算子 string result = (score >= 60) ? "及格" : "不及格";

1.5 流程控制

條件語句:

csharp

// if-else 語句 if (temperature > 30) { Console.WriteLine("天氣炎熱"); } else if (temperature > 20) { Console.WriteLine("天氣舒適"); } else { Console.WriteLine("天氣涼爽"); } // switch 語句 (模式匹配) int day = 3; string dayName = day switch { 1 => "星期一", 2 => "星期二", 3 => "星期三", _ => "其他天" // 預設情況 }; // switch 表達式 (C# 8.0+) var message = day switch { 1 or 7 => "週末", >= 2 and <= 6 => "工作日", _ => "無效" };

迴圈結構:

csharp

// for 迴圈 for (int i = 0; i < 10; i++) { Console.WriteLine($"索引: {i}"); } // foreach 迴圈 string[] colors = { "紅", "綠", "藍" }; foreach (var color in colors) { Console.WriteLine(color); } // while 迴圈 int count = 0; while (count < 5) { Console.WriteLine(count); count++; } // do-while 迴圈 do { Console.WriteLine("至少執行一次"); } while (false);

第二部分:物件導向編程

2.1 類別與物件

類別定義與使用:

csharp

// 基礎類別定義 public class Person { // 欄位 (通常私有) private string _name; // 屬性 (封裝) public string Name { get => _name; set { if (!string.IsNullOrEmpty(value)) _name = value; } } // 自動實作屬性 public int Age { get; set; } // 唯讀屬性 public string Id { get; } // 建構函式 public Person(string name, int age) { Name = name; Age = age; Id = Guid.NewGuid().ToString(); } // 方法 public virtual void Introduce() { Console.WriteLine($"我是{Name},今年{Age}歲"); } // 靜態方法 public static int CalculateBirthYear(int age) { return DateTime.Now.Year - age; } }

2.2 封裝、繼承與多型

繼承與多型:

csharp

// 基類 public abstract class Animal { public string Name { get; set; } public abstract void MakeSound(); public virtual void Move() { Console.WriteLine($"{Name} 正在移動"); } } // 衍生類別 public class Dog : Animal { public string Breed { get; set; } public override void MakeSound() { Console.WriteLine("汪汪!"); } public override void Move() { Console.WriteLine($"{Name} 用四條腿奔跑"); } // 新增方法 public void Fetch() { Console.WriteLine($"{Name} 正在撿球"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("喵喵!"); } } // 使用多型 Animal myPet = new Dog { Name = "Buddy" }; myPet.MakeSound(); // 汪汪!

2.3 介面與抽象類別

介面定義與實作:

csharp

// 介面定義 public interface IRepository<T> { void Add(T item); void Update(T item); void Delete(int id); T GetById(int id); IEnumerable<T> GetAll(); } public interface IAuditable { DateTime CreatedDate { get; set; } string CreatedBy { get; set; } DateTime? ModifiedDate { get; set; } string ModifiedBy { get; set; } } // 實作介面 public class UserRepository : IRepository<User>, IAuditable { public DateTime CreatedDate { get; set; } public string CreatedBy { get; set; } public DateTime? ModifiedDate { get; set; } public string ModifiedBy { get; set; } private List<User> _users = new(); public void Add(User user) { user.Id = _users.Count + 1; _users.Add(user); } // 其他介面方法實作... }

2.4 委派與事件

委派與事件系統:

csharp

// 自訂委派 public delegate void MessageHandler(string message); // 事件發行類別 public class Publisher { // 事件宣告 public event EventHandler<MessageEventArgs> MessageSent; public void SendMessage(string content) { Console.WriteLine($"發送訊息: {content}"); // 觸發事件 OnMessageSent(new MessageEventArgs(content)); } protected virtual void OnMessageSent(MessageEventArgs e) { MessageSent?.Invoke(this, e); } } // 事件參數類別 public class MessageEventArgs : EventArgs { public string Message { get; } public MessageEventArgs(string message) { Message = message; } } // 訂閱者類別 public class Subscriber { public void Subscribe(Publisher publisher) { publisher.MessageSent += HandleMessage; } private void HandleMessage(object sender, MessageEventArgs e) { Console.WriteLine($"收到訊息: {e.Message}"); } }

第三部分:進階 C# 特性

3.1 泛型與集合

泛型程式設計:

csharp

// 泛型類別 public class Repository<T> where T : class, new() { private List<T> _items = new(); public void Add(T item) { _items.Add(item); } public T GetById(int id) where T : IEntity { return _items.FirstOrDefault(x => x.Id == id); } public IEnumerable<T> Find(Func<T, bool> predicate) { return _items.Where(predicate); } } // 泛型方法 public static class Utilities { public static T Max<T>(T a, T b) where T : IComparable<T> { return a.CompareTo(b) > 0 ? a : b; } public static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } }

集合框架:

csharp

// List<T> - 動態陣列 List<string> names = new() { "Alice", "Bob", "Charlie" }; names.Add("David"); names.Remove("Bob"); names.Sort(); // Dictionary<TKey, TValue> - 鍵值對 Dictionary<string, int> ages = new() { ["Alice"] = 25, ["Bob"] = 30 }; if (ages.TryGetValue("Alice", out int age)) { Console.WriteLine($"Alice 的年齡是 {age}"); } // HashSet<T> - 唯一值集合 HashSet<int> uniqueNumbers = new() { 1, 2, 3, 3, 4 }; // 結果: {1, 2, 3, 4} // Queue<T> 和 Stack<T> Queue<string> queue = new(); queue.Enqueue("第一項"); queue.Enqueue("第二項"); string first = queue.Dequeue(); Stack<int> stack = new(); stack.Push(1); stack.Push(2); int top = stack.Pop();

3.2 LINQ 與查詢表達式

LINQ 查詢:

csharp

public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Category { get; set; } } // 資料來源 List<Product> products = new() { new() { Id = 1, Name = "筆記本", Price = 100, Category = "文具" }, new() { Id = 2, Name = "手機", Price = 20000, Category = "電子" }, new() { Id = 3, Name = "書", Price = 300, Category = "文具" }, new() { Id = 4, Name = "耳機", Price = 1500, Category = "電子" } }; // 方法語法 var expensiveProducts = products .Where(p => p.Price > 500) .OrderByDescending(p => p.Price) .Select(p => new { p.Name, p.Price }); // 查詢表達式語法 var query = from p in products where p.Price > 500 orderby p.Price descending select new { p.Name, p.Price }; // 分組查詢 var productsByCategory = from p in products group p by p.Category into g select new { Category = g.Key, Count = g.Count(), TotalPrice = g.Sum(p => p.Price) }; // 連接查詢 var orders = new List<Order> { /* 訂單資料 */ }; var orderDetails = from o in orders join p in products on o.ProductId equals p.Id select new { o.OrderId, p.Name, o.Quantity };

3.3 非同步編程

async/await 模式:

csharp

public class AsyncExample { // 非同步方法 public async Task<string> DownloadContentAsync(string url) { using HttpClient client = new(); try { // 非同步下載 string content = await client.GetStringAsync(url); return content; } catch (HttpRequestException ex) { Console.WriteLine($"下載失敗: {ex.Message}"); return string.Empty; } } // 並行執行多個任務 public async Task ProcessMultipleUrlsAsync() { var urls = new[] { "https://api.example.com/data1", "https://api.example.com/data2", "https://api.example.com/data3" }; // 同時開始所有下載 var downloadTasks = urls.Select(url => DownloadContentAsync(url)); // 等待所有完成 string[] contents = await Task.WhenAll(downloadTasks); // 處理結果 foreach (var content in contents) { Console.WriteLine($"下載內容長度: {content.Length}"); } } // 非同步事件處理 public event Func<object, EventArgs, Task> DataLoaded; public async Task LoadDataAsync() { // 模擬長時間操作 await Task.Delay(1000); // 觸發非同步事件 if (DataLoaded != null) await DataLoaded.Invoke(this, EventArgs.Empty); } } // 非同步主方法 (C# 7.1+) class Program { static async Task Main(string[] args) { var example = new AsyncExample(); string content = await example.DownloadContentAsync("https://example.com"); Console.WriteLine(content); } }

3.4 屬性與反射

自訂屬性:

csharp

// 自訂屬性類別 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public class AuthorAttribute : Attribute { public string Name { get; } public DateTime Date { get; set; } public AuthorAttribute(string name) { Name = name; Date = DateTime.Now; } } // 使用自訂屬性 [Author("張三", Date = "2024-01-15")] public class Calculator { [Author("李四")] public int Add(int a, int b) => a + b; }

反射機制:

csharp

public class ReflectionExample { public void InspectType(Type type) { Console.WriteLine($"類型名稱: {type.Name}"); Console.WriteLine($"完整名稱: {type.FullName}"); // 獲取屬性 var properties = type.GetProperties(); foreach (var prop in properties) { Console.WriteLine($"屬性: {prop.Name} ({prop.PropertyType.Name})"); } // 獲取方法 var methods = type.GetMethods(); foreach (var method in methods) { Console.WriteLine($"方法: {method.Name}"); } // 檢查自訂屬性 var attributes = type.GetCustomAttributes(typeof(AuthorAttribute), false); foreach (AuthorAttribute attr in attributes) { Console.WriteLine($"作者: {attr.Name}, 日期: {attr.Date}"); } } // 動態建立實例 public object CreateInstance(string typeName) { Type type = Type.GetType(typeName); if (type == null) return null; return Activator.CreateInstance(type); } // 動態調用方法 public object InvokeMethod(object obj, string methodName, params object[] args) { Type type = obj.GetType(); var method = type.GetMethod(methodName); if (method != null) { return method.Invoke(obj, args); } return null; } }

第四部分:實際應用與最佳實踐

4.1 錯誤處理與例外

例外處理模式:

csharp

public class ExceptionHandlingExample { public void ProcessFile(string filePath) { try { // 嘗試開啟檔案 using var stream = new FileStream(filePath, FileMode.Open); using var reader = new StreamReader(stream); string content = reader.ReadToEnd(); Console.WriteLine($"檔案內容: {content}"); } catch (FileNotFoundException ex) { Console.WriteLine($"檔案不存在: {ex.FileName}"); // 記錄日誌 Logger.LogError($"File not found: {filePath}", ex); } catch (IOException ex) when (ex is DirectoryNotFoundException || ex is PathTooLongException) { Console.WriteLine($"路徑問題: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"未知錯誤: {ex.Message}"); throw; // 重新拋出 } finally { // 清理資源 Console.WriteLine("清理完成"); } } // 自訂例外類別 public class CustomException : Exception { public int ErrorCode { get; } public CustomException(string message, int errorCode) : base(message) { ErrorCode = errorCode; } public CustomException(string message, int errorCode, Exception innerException) : base(message, innerException) { ErrorCode = errorCode; } } }

4.2 設計模式實作

常用設計模式:

csharp

// 單例模式 public sealed class DatabaseConnection { private static readonly Lazy<DatabaseConnection> _instance = new Lazy<DatabaseConnection>(() => new DatabaseConnection()); public static DatabaseConnection Instance => _instance.Value; private DatabaseConnection() { // 初始化連接 } public void Connect() { Console.WriteLine("資料庫已連接"); } } // 工廠模式 public interface IShape { void Draw(); } public class Circle : IShape { public void Draw() => Console.WriteLine("繪製圓形"); } public class Rectangle : IShape { public void Draw() => Console.WriteLine("繪製矩形"); } public class ShapeFactory { public IShape CreateShape(string type) { return type.ToLower() switch { "circle" => new Circle(), "rectangle" => new Rectangle(), _ => throw new ArgumentException("不支援的形狀") }; } } // 觀察者模式 public class WeatherStation : IObservable<WeatherData> { private List<IObserver<WeatherData>> _observers = new(); private WeatherData _currentWeather; public IDisposable Subscribe(IObserver<WeatherData> observer) { _observers.Add(observer); return new Unsubscriber(_observers, observer); } public void SetWeather(WeatherData weather) { _currentWeather = weather; foreach (var observer in _observers) { observer.OnNext(_currentWeather); } } private class Unsubscriber : IDisposable { private List<IObserver<WeatherData>> _observers; private IObserver<WeatherData> _observer; public Unsubscriber(List<IObserver<WeatherData>> observers, IObserver<WeatherData> observer) { _observers = observers; _observer = observer; } public void Dispose() { if (_observer != null && _observers.Contains(_observer)) _observers.Remove(_observer); } } }

4.3 效能優化與記憶體管理

效能最佳實踐:

csharp

public class PerformanceOptimization { // 使用 StringBuilder 處理大量字串 public string BuildLargeString() { var sb = new StringBuilder(); for (int i = 0; i < 10000; i++) { sb.Append(i.ToString()); } return sb.ToString(); // 比字串連接高效 } // 結構體 vs 類別 public struct PointStruct // 適合小型、不可變資料 { public int X { get; } public int Y { get; } public PointStruct(int x, int y) { X = x; Y = y; } } // 使用 ArrayPool 減少記憶體分配 public void ProcessWithArrayPool() { var pool = ArrayPool<int>.Shared; int[] array = pool.Rent(1024); // 從池中租用 try { // 使用陣列 for (int i = 0; i < array.Length; i++) { array[i] = i; } } finally { pool.Return(array); // 歸還到池中 } } // 避免裝箱拆箱 public void AvoidBoxing() { // 不好 - 會裝箱 ArrayList oldList = new ArrayList(); oldList.Add(1); // 裝箱發生 // 好 - 泛型避免裝箱 List<int> newList = new List<int>(); newList.Add(1); // 無裝箱 } // 延遲執行與緩存 public class DataService { private Lazy<List<string>> _cachedData = new Lazy<List<string>>(() => LoadDataFromDatabase()); public List<string> GetData() { return _cachedData.Value; // 第一次呼叫時載入 } private List<string> LoadDataFromDatabase() { // 模擬耗時操作 Thread.Sleep(1000); return new List<string> { "資料1", "資料2", "資料3" }; } } }

4.4 單元測試與除錯

單元測試實作:

csharp

// 測試專案通常使用 xUnit、NUnit 或 MSTest public class CalculatorTests { [Theory] [InlineData(1, 2, 3)] [InlineData(0, 0, 0)] [InlineData(-1, 1, 0)] public void Add_ShouldReturnCorrectSum(int a, int b, int expected) { // 準備 var calculator = new Calculator(); // 執行 int result = calculator.Add(a, b); // 驗證 Assert.Equal(expected, result); } [Fact] public void Divide_ByZero_ShouldThrowException() { // 準備 var calculator = new Calculator(); // 執行與驗證 Assert.Throws<DivideByZeroException>(() => calculator.Divide(10, 0)); } } // 模擬與依賴注入 public interface IDataService { string GetData(); } public class DataProcessor { private readonly IDataService _dataService; public DataProcessor(IDataService dataService) { _dataService = dataService; } public string Process() { string data = _dataService.GetData(); return data.ToUpper(); } } // 使用 Moq 進行模擬 [Fact] public void Process_ShouldReturnUppercaseData() { // 建立模擬物件 var mockService = new Mock<IDataService>(); mockService.Setup(x => x.GetData()).Returns("test data"); // 建立測試物件 var processor = new DataProcessor(mockService.Object); // 執行測試 string result = processor.Process(); // 驗證 Assert.Equal("TEST DATA", result); mockService.Verify(x => x.GetData(), Times.Once); }

結論

C# 是一個功能強大且不斷發展的程式語言,從基礎的語法結構到進階的非同步編程和模式匹配,它提供了豐富的工具來解決各種編程問題。掌握 C# 不僅需要理解語法,更重要的是學會如何:

  1. 寫出可維護的程式碼:遵循 SOLID 原則,使用適當的設計模式

  2. 確保程式效能:理解記憶體管理,避免常見的效能陷阱

  3. 建置可靠的系統:實作全面的錯誤處理和測試策略

  4. 跟上語言發展:學習並應用 C# 的新特性

無論是開發桌面應用、Web 服務、行動應用還是遊戲,C# 都是強大的選擇。持續學習、實踐並參與社群,將幫助你從 C# 入門者成長為精通者。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/7 8:39:25

突破网盘下载限制!这款神器让你告别龟速下载

突破网盘下载限制&#xff01;这款神器让你告别龟速下载 【免费下载链接】netdisk-fast-download 各类网盘直链解析, 已支持蓝奏云/奶牛快传/移动云云空间/UC网盘/小飞机盘/亿方云/123云盘等. 预览地址 https://lz.qaiu.top 项目地址: https://gitcode.com/gh_mirrors/ne/net…

作者头像 李华
网站建设 2026/2/5 6:11:30

Day 40 复习日

浙大疏锦行 用 MLP 神经网络训练&#xff0c;并且让代码更规范美观&#xff0c;用到之前讲的知识点比如类的 call 方法、模型评估、GPU 训练、模型结构可视化等。 首先&#xff0c;梳理步骤&#xff1a; 代码重构&#xff0c;模块化&#xff1a;把预处理、模型构建、训练、评…

作者头像 李华
网站建设 2026/2/5 23:32:36

Unity游戏翻译插件快速上手:完整多语言解决方案实战指南

Unity游戏翻译插件快速上手&#xff1a;完整多语言解决方案实战指南 【免费下载链接】XUnity.AutoTranslator 项目地址: https://gitcode.com/gh_mirrors/xu/XUnity.AutoTranslator 想要为Unity游戏添加多语言支持吗&#xff1f;XUnity.AutoTranslator作为功能强大的Un…

作者头像 李华
网站建设 2026/2/6 0:53:39

百度网盘直链解析:解锁高速下载新体验

在数字化浪潮席卷的今天&#xff0c;百度网盘已成为我们存储知识、分享智慧的数字宝库。然而&#xff0c;下载速度的瓶颈如同一条无形的锁链&#xff0c;束缚着我们对知识的渴求。现在&#xff0c;一款名为baidu-wangpan-parse的工具横空出世&#xff0c;将为您打开通往高速下载…

作者头像 李华
网站建设 2026/2/3 0:35:36

LobeChat能否对接Slack频道?团队协作工具集成方案

LobeChat 能否对接 Slack 频道&#xff1f;团队协作工具集成方案 在今天的远程办公常态下&#xff0c;Slack 已经不仅是聊天工具&#xff0c;而是团队的信息中枢——任务分配、项目同步、故障告警、知识共享&#xff0c;几乎所有的协作行为都围绕着频道展开。但问题也随之而来&…

作者头像 李华
网站建设 2026/2/5 23:21:08

【数据结构】C语言实现队列(Queue):链式存储与操作详解

文章目录前言 &#x1f680;一、队列的概念 &#x1f4a1;1. 什么是队列&#xff1f;2. 队列有什么用&#xff1f;二、队列的模拟实现 &#x1f6e0;️1. 选型&#xff1a;数组 vs 链表&#xff1f;2. 代码实现2.1 结构体定义2.2 初始化2.3 入队 (Push)2.4 出队 (Pop)2.5 获取队…

作者头像 李华