一、方法基礎語法?
C#方法是封裝代碼邏輯的基本單元,用于執行特定操作并支持模塊化編程?。
- 定義與結構?
C#方法由訪問修飾符、返回值、方法名、參數列表和方法體構成。基礎語法如下:
[訪問修飾符] [static] 返回值類型 方法名(參數列表)
{ // 方法體
}
- 訪問修飾符?:public、private 等控制方法可見性,默認類內方法為 private?。
- 返回值?:無返回值時使用 void,否則需聲明具體類型(如 int、string)?。
- 參數傳遞?
- 值類型與引用類型?:值類型參數傳遞副本,引用類型(如類對象)傳遞內存地址?。
- ?可選參數?:通過默認值實現,調用時可省略:
public void Print(string text, bool isBold = false) { ... }
Print("Hello"); // 自動使用 isBold = false
- ?命名參數?:調用時指定參數名,提高可讀性:
Print(isBold: true, text: "Warning");
- 可變參數?:使用 params 接收數組:
public int Sum(params int[] numbers) { ... }
Sum(1, 2, 3);
二、方法重載與特殊類型?
- 方法重載?
同一類中允許定義多個同名方法,?參數列表必須不同?(類型、數量或順序):
public void Log(int code) { ... }
public void Log(string message) { ... } // 合法重載
注:返回值類型不參與重載判定?。
- 靜態方法?
- 使用 static 修飾,直接通過類名調用,無需實例化對象?46。
- 示例:
public static class MathUtils
{ public static int Add(int a, int b) => a + b;
}
int sum = MathUtils.Add(3, 5);
- 擴展方法?
通過 this 關鍵字為現有類型添加新方法,需在靜態類中定義:
public static class StringExtensions
{ public static bool IsNumeric(this string str) { return int.TryParse(str, out _); }
}
bool result = "123".IsNumeric(); // 返回 true
- 構造函數?
用于初始化對象,與類同名且無返回值:
public class Person
{ public string Name { get; set; } public Person(string name) => Name = name;
}
三、高級方法特性?
- 異步方法?
使用 async/await 實現非阻塞操作,適用于I/O密集型任務:
public async Task<string> FetchDataAsync(string url)
{ HttpClient client = new HttpClient(); return await client.GetStringAsync(url);
}
注:異步方法需返回 Task 或 Task 類型?。
- ?Lambda表達式?
簡化匿名方法的定義:
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 輸出 25
- ?遞歸方法?
方法直接或間接調用自身,需注意終止條件:
public int Factorial(int n)
{ if (n == 0) return 1; return n * Factorial(n - 1);
}
四、使用建議
- 代碼規范?
- 單一職責原則?:每個方法僅完成一個明確任務?。
- 命名清晰?:方法名使用動詞短語(如 CalculateTax、ValidateInput)。