聊城做网站费用,微信小程序在哪里找?,全国十大软件开发培训机构,wordpress管局备案C# 從入門到精通#xff1a;全方位掌握現代程式語言第一部分#xff1a;C# 入門基礎1.1 C# 概述與發展歷程C##xff08;發音為 C Sharp#xff09;是由微軟在 2000 年推出的現代化、物件導向的程式語言。它結合了 C 的強大功能與 Java 的簡潔性#xff0c;並…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 Codebash# 安裝必要擴充功能 # - C# for Visual Studio Code # - .NET Core Debugger # - NuGet Package Manager.NET CLI 基本指令bashdotnet --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 運算子與表達式算術運算子csharpint 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; // x6, y6 (前置) int z x; // z6, x7 (後置)比較與邏輯運算子csharpbool 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 IRepositoryT { void Add(T item); void Update(T item); void Delete(int id); T GetById(int id); IEnumerableT GetAll(); } public interface IAuditable { DateTime CreatedDate { get; set; } string CreatedBy { get; set; } DateTime? ModifiedDate { get; set; } string ModifiedBy { get; set; } } // 實作介面 public class UserRepository : IRepositoryUser, IAuditable { public DateTime CreatedDate { get; set; } public string CreatedBy { get; set; } public DateTime? ModifiedDate { get; set; } public string ModifiedBy { get; set; } private ListUser _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 EventHandlerMessageEventArgs 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 RepositoryT where T : class, new() { private ListT _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 IEnumerableT Find(FuncT, bool predicate) { return _items.Where(predicate); } } // 泛型方法 public static class Utilities { public static T MaxT(T a, T b) where T : IComparableT { return a.CompareTo(b) 0 ? a : b; } public static void SwapT(ref T a, ref T b) { T temp a; a b; b temp; } }集合框架csharp// ListT - 動態陣列 Liststring names new() { Alice, Bob, Charlie }; names.Add(David); names.Remove(Bob); names.Sort(); // DictionaryTKey, TValue - 鍵值對 Dictionarystring, int ages new() { [Alice] 25, [Bob] 30 }; if (ages.TryGetValue(Alice, out int age)) { Console.WriteLine($Alice 的年齡是 {age}); } // HashSetT - 唯一值集合 HashSetint uniqueNumbers new() { 1, 2, 3, 3, 4 }; // 結果: {1, 2, 3, 4} // QueueT 和 StackT Queuestring queue new(); queue.Enqueue(第一項); queue.Enqueue(第二項); string first queue.Dequeue(); Stackint stack new(); stack.Push(1); stack.Push(2); int top stack.Pop();3.2 LINQ 與查詢表達式LINQ 查詢csharppublic class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Category { get; set; } } // 資料來源 ListProduct 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 ListOrder { /* 訂單資料 */ }; 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 模式csharppublic class AsyncExample { // 非同步方法 public async Taskstring 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 Funcobject, 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; }反射機制csharppublic 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 錯誤處理與例外例外處理模式csharppublic 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 LazyDatabaseConnection _instance new LazyDatabaseConnection(() 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 : IObservableWeatherData { private ListIObserverWeatherData _observers new(); private WeatherData _currentWeather; public IDisposable Subscribe(IObserverWeatherData 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 ListIObserverWeatherData _observers; private IObserverWeatherData _observer; public Unsubscriber(ListIObserverWeatherData observers, IObserverWeatherData observer) { _observers observers; _observer observer; } public void Dispose() { if (_observer ! null _observers.Contains(_observer)) _observers.Remove(_observer); } } }4.3 效能優化與記憶體管理效能最佳實踐csharppublic 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 ArrayPoolint.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); // 裝箱發生 // 好 - 泛型避免裝箱 Listint newList new Listint(); newList.Add(1); // 無裝箱 } // 延遲執行與緩存 public class DataService { private LazyListstring _cachedData new LazyListstring(() LoadDataFromDatabase()); public Liststring GetData() { return _cachedData.Value; // 第一次呼叫時載入 } private Liststring LoadDataFromDatabase() { // 模擬耗時操作 Thread.Sleep(1000); return new Liststring { 資料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.ThrowsDivideByZeroException(() 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 MockIDataService(); 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# 不僅需要理解語法更重要的是學會如何寫出可維護的程式碼遵循 SOLID 原則使用適當的設計模式確保程式效能理解記憶體管理避免常見的效能陷阱建置可靠的系統實作全面的錯誤處理和測試策略跟上語言發展學習並應用 C# 的新特性無論是開發桌面應用、Web 服務、行動應用還是遊戲C# 都是強大的選擇。持續學習、實踐並參與社群將幫助你從 C# 入門者成長為精通者。