C# - 方法
方法是一组共同执行一项任务的语句。每个 C# 程序至少有一个包含名为 Main 的方法的类。
要使用方法,您需要:-
- 定义方法
- 调用方法
在 C# 中定义方法
定义方法时,基本上就是声明其结构的元素。在 C# 中定义方法的语法如下:-
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}
以下是方法的各个元素 -
访问说明符 - 这决定了变量或方法对其他类的可见性。
返回类型 - 方法可以返回一个值。返回类型是方法返回值的数据类型。如果方法不返回任何值,则返回类型为void。
方法名称 - 方法名称是唯一标识符,并且区分大小写。它不能与类中声明的任何其他标识符相同。
参数列表 - 参数括在括号中,用于传递和接收方法中的数据。参数列表指的是方法参数的类型、顺序和数量。参数是可选的;也就是说,方法可以不包含任何参数。
方法主体 − 包含完成所需操作所需的一组指令。
示例
以下代码片段展示了一个函数 FindMax,它接受两个整数值并返回其中较大的一个。它具有 public 访问说明符,因此可以使用类的实例从类外部访问它。
class NumberManipulator {
public int FindMax(int num1, int num2) {
/*局部变量声明*/
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
...
}
在 C# 中调用方法
您可以使用方法名称来调用方法。以下示例对此进行了说明 -
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;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//调用 FindMax 方法
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}
当编译并执行上述代码时,它会产生以下结果 -
Max value is : 200
您也可以使用类的实例从其他类调用公共方法。例如,方法 FindMax 属于 NumberManipulator 类,您可以从另一个类 Test 调用它。
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;
}
}
class Test {
static void Main(string[] args) {
/* 局部变量定义 */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//调用 FindMax 方法
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) {
/*局部变量声明*/
int result;
if (num == 1) {
return 1;
} else {
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
//calling the factorial method {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 | 引用参数
此方法将对实际参数内存位置的引用复制到形式参数中。这意味着对形参的更改会影响实际参数。 |
| 3 | 输出参数
此方法有助于返回多个值。 |

