C# 方法完全指南:定义、调用、递归与参数传递
方法是一组共同执行任务的语句。每个 C# 程序至少包含一个带有 Main 方法的类。
使用方法需两步:
- 定义方法
- 调用方法
定义方法
定义方法时声明其结构要素。语法:
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}
方法要素
- 访问修饰符:决定从其他类访问变量或方法的可见性。
- 返回类型:方法可能返回值,返回类型是返回值的数据类型。无返回值则为
void。 - 方法名:唯一标识符,区分大小写,不能与类中其他标识符同名。
- 参数列表:括号内的参数用于传递和接收数据。指定参数类型、顺序、数量。参数可选。
- 方法体:包含完成所需活动的指令集。
示例:FindMax 方法
class NumberManipulator {
public int FindMax(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
调用方法
通过方法名调用。示例:
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
static void Main(string[] args) {
int a = 100, b = 200, ret;
NumberManipulator n = new NumberManipulator();
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret);
Console.ReadLine();
}
}
}
输出:
Max value is : 200
也可从其他类通过类实例调用公共方法。
递归方法调用
方法可调用自身,称为递归。示例:计算阶乘
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int factorial(int num) {
if (num == 1) return 1;
else return factorial(num - 1) * num;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
输出:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
参数传递方式
| 序号 | 机制及说明 |
|---|---|
| 1 | 值参数:将实参实际值复制给形参。函数内修改形参不影响实参。 |
| 2 | 引用参数:将实参内存地址引用复制给形参。修改形参影响实参(使用 ref 关键字)。 |
| 3 | 输出参数:用于返回多个值(使用 out 关键字)。 |
参数传递示例
// 值参数
void SwapByValue(int a, int b) { int t = a; a = b; b = t; }
// 引用参数
void SwapByRef(ref int a, ref int b) { int t = a; a = b; b = t; }
// 输出参数
void GetValues(out int a, out int b) { a = 10; b = 20; }
注意:ref 要求实参在传递前已初始化;out 不要求初始化,但方法必须在返回前为所有 out 参数赋值。C# 7.0+ 还支持 in(只读引用)和 ref readonly。
C语言