1.?基礎語法結構
C# 程序由命名空間、類和方法組成。每個程序必須有一個?Main
?方法作為入口點。using
?指令用于導入命名空間,Console.WriteLine()
?是常用的輸出方法。
csharp
復制
下載
using System; // 引入核心命名空間class Program // 類定義 {static void Main() // 程序入口方法{Console.WriteLine("Hello C#!"); // 控制臺輸出} }
2.?數據類型
C# 是強類型語言,所有變量必須聲明類型:
類型 | 示例 | 說明 |
---|---|---|
int | int age = 25; | 32位整數,范圍: -231 到 231-1 |
double | double pi = 3.14; | 64位雙精度浮點數 |
bool | bool isActive = true; | 布爾值(true/false) |
char | char symbol = '#'; | 單個Unicode字符 |
string | string name = "Alice"; | Unicode字符串 |
decimal | decimal price = 19.99m; | 128位精確十進制數,適合金融計算 |
3.?變量與常量
-
變量:存儲可變值,使用前必須聲明類型
-
常量:使用?
const
?聲明,值不可變 -
類型推斷:
var
?關鍵字讓編譯器推斷類型
csharp
復制
下載
int counter = 10; // 顯式類型聲明 const double TAX_RATE = 0.2; // 常量 var message = "Hello"; // 編譯器推斷為string類型
4.?運算符
C# 包含多種運算符類型:
-
算術運算符:
+
,?-
,?*
,?/
,?%
-
比較運算符:
==
,?!=
,?>
,?<
,?>=
,?<=
-
邏輯運算符:
&&
?(AND),?||
?(OR),?!
?(NOT) -
賦值運算符:
=
,?+=
,?-=
,?*=
csharp
復制
下載
int x = 15, y = 4; double quotient = x / (double)y; // 3.75 (需類型轉換) bool isEven = (x % 2 == 0); // 檢查偶數
5.?控制流程
控制程序執行流程的結構:
條件語句
csharp
復制
下載
int temperature = 22;if (temperature > 30)Console.WriteLine("炎熱"); else if (temperature > 20)Console.WriteLine("舒適"); // 輸出此項 elseConsole.WriteLine("涼爽");
循環語句
csharp
復制
下載
// for 循環:精確控制迭代次數 for (int i = 1; i <= 5; i++) {Console.Write(i + " "); // 輸出: 1 2 3 4 5 }// while 循環:條件滿足時執行 int count = 3; while (count > 0) {Console.Write(count-- + " "); // 輸出: 3 2 1 }
6.?數組
存儲相同類型元素的集合:
-
一維數組:線性數據集合
-
多維數組:表格結構數據
-
索引從0開始
csharp
復制
下載
// 一維數組 string[] colors = { "紅", "綠", "藍" }; Console.WriteLine(colors[0]); // 輸出"紅"// 二維數組 int[,] grid = { {1, 2}, {3, 4}, {5, 6} }; Console.WriteLine(grid[2, 0]); // 輸出5
7.?方法(函數)
封裝可重用代碼塊:
-
可接收參數
-
可返回結果
-
提高代碼復用性
csharp
復制
下載
// 方法定義 static double CalculateCircleArea(double radius) {return Math.PI * radius * radius; }// 方法調用 double area = CalculateCircleArea(5.0); Console.WriteLine($"圓面積: {area:F2}"); // 輸出: 圓面積: 78.54
8.?類與對象
面向對象編程的核心:
-
類:對象的藍圖模板
-
對象:類的具體實例
-
屬性:描述對象特征
-
方法:對象的行為
csharp
復制
下載
class Book {// 屬性public string Title { get; set; }public string Author { get; set; }// 方法public void DisplayInfo() {Console.WriteLine($"《{Title}》, 作者: {Author}");} }// 創建對象 Book myBook = new Book(); myBook.Title = "C#入門經典"; myBook.Author = "John Doe"; myBook.DisplayInfo(); // 輸出書籍信息
9.?繼承與多態
OOP 的核心特性:
-
繼承:子類繼承父類特性
-
多態:不同對象對同一消息有不同響應
-
方法重寫:使用?
virtual
?和?override
csharp
復制
下載
class Vehicle // 基類 {public virtual void StartEngine() {Console.WriteLine("引擎啟動");} }class Car : Vehicle // 繼承 {public override void StartEngine() // 方法重寫{Console.WriteLine("汽車引擎啟動");} }// 多態示例 Vehicle myVehicle = new Car(); myVehicle.StartEngine(); // 輸出"汽車引擎啟動"
10.?異常處理
處理運行時錯誤的機制:
-
try
:包含可能出錯的代碼 -
catch
:捕獲并處理異常 -
finally
:無論是否異常都會執行
csharp
復制
下載
try {int[] nums = { 1, 2, 3 };Console.WriteLine(nums[5]); // 索引超出范圍 } catch (IndexOutOfRangeException ex) // 捕獲特定異常 {Console.WriteLine($"錯誤: {ex.Message}"); } catch (Exception ex) // 通用異常捕獲 {Console.WriteLine($"未知錯誤: {ex.Message}"); } finally {Console.WriteLine("清理資源完成"); }
11.?字符串操作
字符串是引用類型,常用操作:
-
拼接:
+
?或?$"{}"
-
格式化:
ToUpper()
,?ToLower()
-
查詢:
Contains()
,?IndexOf()
-
截取:
Substring()
csharp
復制
下載
string greeting = " Hello C# "; Console.WriteLine(greeting.Trim()); // 移除空格: "Hello C#" Console.WriteLine(greeting.ToUpper()); // 轉大寫: " HELLO C# " Console.WriteLine(greeting.Contains("C#")); // 檢查包含: True Console.WriteLine($"長度: {greeting.Length}"); // 字符串插值
12.?集合類型
System.Collections.Generic
?命名空間提供:
-
List<T>:動態數組
-
Dictionary<TKey,TValue>:鍵值對集合
-
Queue<T>:先進先出隊列
-
Stack<T>:后進先出堆棧
csharp
復制
下載
using System.Collections.Generic;// List示例 List<int> numbers = new List<int> { 10, 20, 30 }; numbers.Add(40); Console.WriteLine($"第二個元素: {numbers[1]}"); // 20// Dictionary示例 Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Alice", 28); ages["Bob"] = 32; // 另一種添加方式 Console.WriteLine($"Alice的年齡: {ages["Alice"]}");
完整案例:學生成績管理系統
csharp
復制
下載
using System; using System.Collections.Generic;class Student {public string Name { get; set; }public List<int> Grades { get; } = new List<int>();public void AddGrade(int grade) {if (grade < 0 || grade > 100)throw new ArgumentException("成績必須在0-100之間");Grades.Add(grade);}public double CalculateAverage(){if (Grades.Count == 0) return 0;double sum = 0;foreach (int grade in Grades)sum += grade;return sum / Grades.Count;} }class Program {static void Main(){try{Student student = new Student { Name = "張三" };student.AddGrade(85);student.AddGrade(92);student.AddGrade(78);Console.WriteLine($"{student.Name}的平均成績: {student.CalculateAverage():F1}");}catch (Exception ex){Console.WriteLine($"錯誤: {ex.Message}");}} }
程序說明:
-
創建?
Student
?類管理學生信息和成績 -
使用?
List<int>
?存儲多個成績 -
實現成績添加和平均分計算方法
-
添加異常處理確保成績有效性
-
主程序創建學生對象并計算平均分
輸出:
text
復制
下載
張三的平均成績: 85.0
關鍵概念總結
概念 | 說明 |
---|---|
面向對象 | 封裝、繼承、多態三大特性,使用類(class)和對象(object)構建程序 |
類型系統 | 值類型(int, struct)直接存儲值,引用類型(class, string)存儲內存地址 |
內存管理 | 自動垃圾回收(GC),using ?語句管理資源釋放 |
核心特性 | 屬性(Properties)、索引器、委托(Delegates)、事件(Events) |
高級功能 | LINQ(語言集成查詢)、異步編程(async/await)、反射(Reflection) |
開發框架 | .NET Framework/.NET Core,支持控制臺、Web(ASP.NET)、桌面(WinForms/WPF)等應用 |
學習路線建議:
掌握基礎語法和OOP概念
學習常用.NET類庫(集合、文件IO、網絡)
實踐數據庫操作(ADO.NET/Entity Framework)
探索高級主題(異步編程、LINQ、依賴注入)
構建實際項目(Web API、桌面應用)