C Sharp 方法定义
外观
C#方法定义[编辑 | 编辑源代码]
方法(Method)是C#编程中的基本构建块之一,用于封装可重用的代码逻辑。方法允许开发者将复杂任务分解为更小、更易管理的单元,从而提高代码的可读性、可维护性和复用性。
1. 基本语法[编辑 | 编辑源代码]
C#方法的定义包含以下关键部分:
[访问修饰符] [返回类型] 方法名称([参数列表])
{
// 方法体
[return 返回值;]
}
- 访问修饰符:控制方法的可见性(如 `public`、`private`)。
- 返回类型:方法返回的数据类型(如 `int`、`string`),若无需返回值则用 `void`。
- 方法名称:遵循PascalCase命名规范。
- 参数列表:可选,用于传递输入值。
示例:简单方法[编辑 | 编辑源代码]
public int Add(int a, int b)
{
return a + b;
}
调用与输出:
int result = Add(3, 5);
Console.WriteLine(result); // 输出:8
2. 方法参数类型[编辑 | 编辑源代码]
C#支持多种参数传递方式:
2.1 值参数(默认)[编辑 | 编辑源代码]
传递参数的副本,原始值不受影响。
public void Square(int number)
{
number *= number;
Console.WriteLine($"方法内: {number}");
}
// 调用
int num = 4;
Square(num);
Console.WriteLine($"方法外: {num}");
// 输出:
// 方法内: 16
// 方法外: 4
2.2 引用参数(ref)[编辑 | 编辑源代码]
传递内存地址,修改会影响原始变量。
public void SquareRef(ref int number)
{
number *= number;
}
// 调用
int num = 4;
SquareRef(ref num);
Console.WriteLine(num); // 输出:16
2.3 输出参数(out)[编辑 | 编辑源代码]
用于从方法返回多个值,无需初始化输入。
public void Divide(int dividend, int divisor, out int quotient, out int remainder)
{
quotient = dividend / divisor;
remainder = dividend % divisor;
}
// 调用
Divide(10, 3, out int q, out int r);
Console.WriteLine($"商: {q}, 余数: {r}"); // 输出:商: 3, 余数: 1
3. 方法重载[编辑 | 编辑源代码]
同一作用域内可定义多个同名方法,只要参数列表不同。
public int Multiply(int a, int b) => a * b;
public double Multiply(double a, double b) => a * b;
// 调用
Console.WriteLine(Multiply(2, 3)); // 输出:6
Console.WriteLine(Multiply(2.5, 3.5)); // 输出:8.75
4. 实际应用案例[编辑 | 编辑源代码]
案例:用户验证系统[编辑 | 编辑源代码]
public bool ValidateUser(string username, string password, out string errorMessage)
{
if (string.IsNullOrEmpty(username))
{
errorMessage = "用户名不能为空";
return false;
}
if (password.Length < 8)
{
errorMessage = "密码至少8位";
return false;
}
errorMessage = "";
return true;
}
// 调用
if (ValidateUser("admin", "12345678", out string message))
{
Console.WriteLine("验证成功");
}
else
{
Console.WriteLine($"错误: {message}");
}
5. 高级主题:表达式体方法[编辑 | 编辑源代码]
C# 6+ 支持单行方法的简写语法:
public string Greet(string name) => $"Hello, {name}!";
6. 方法调用流程(Mermaid图)[编辑 | 编辑源代码]
7. 数学公式示例[编辑 | 编辑源代码]
若方法涉及数学计算,可用公式表示: 计算圆的面积:
对应方法实现:
public double CalculateCircleArea(double radius) => Math.PI * Math.Pow(radius, 2);
总结[编辑 | 编辑源代码]
- 方法是封装代码逻辑的基本单元。
- 参数传递方式包括值参数、引用参数和输出参数。
- 方法重载提高代码灵活性,表达式体简化单行方法。
- 实际开发中,方法常用于模块化复杂业务逻辑。