函数是指一段被封装起来且能实现一定功能的代码。
以下两种情况,可考虑使用函数实现:
(1)程序中可能重复出现相同或相似的代码,从中抽取出共同的部分,定义为函数,使该功能定义一次,可以多次使用,从而有效减少代码量,提高代码的重用率。
(2)程序中具有逻辑独立性的代码,即使该段代码只出现一次,也可以定义为函数,用于分解程序的复杂性,使程序结构更加清晰,更容易理解。
函数的语法:
修饰符 返回值类型 方法名(参数类型 参数名){
...
方法体
...
return 返回值;
}
一、无参数,无返回值函数
函数定义:
public static void PrintHello()
{
Console.WriteLine("hello,welcome to 1702!");
}
函数调用:
static void Main(string[] args)
{
PrintHello();
}
二、有参数,无返回值函数
函数定义:
//接受一个圆半径,求出圆面积
public static void ComputeYuanArea(double r)
{
double area = 3.14 * r * r;
Console.WriteLine("圆面积:" + area);
}
//接受一个长方形的长和宽,求长方形的面积
public static void ComputeCfxArea(int c,int k)
{
double area = c * k;
Console.WriteLine("长方形面积:" + area);
}
函数调用:
static void Main(string[] args)
{
ComputeYuanArea(5);
ComputeCfxArea(5, 6);
}
三、有参数,有返回值函数
函数定义:
//有参,有返回值(接受一个圆半径,求出圆面积)
public static double ComputeYuanArea(double r)
{
double area = 3.14 * r * r;
return area;
}
//有参,有返回值(接受一个长方形的长和宽,求长方形的面积)
public static int ComputeCfxArea(int c, int k)
{
int area = c * k;
return area;
}
函数调用:
static void Main(string[] args)
{
//求圆面积与长方形面积的和
double allArea = ComputeYuanArea(5) + ComputeCfxArea(5, 6);
Console.WriteLine("总面积:" + allArea);
}
四、深入了解参数传递
编写函数实现两个数字交换:
方案一:
函数定义:
public static void exchange(int a, int b)
{
int c = a;
a = b;
b = c;
}
函数调用:
static void Main(string[] args)
{
int a = 10;
int b = 20;
exchange(a,b);
Console.WriteLine(a);
Console.WriteLine(b);
}
我们会发现此方案并不成立,两个数字并没有交换,原因是此时参数传递,传递的是值,而不是引用;
即基本数据类型作为参数的时候,方法里面值发生改变,调用的地方不变。
方案二:
函数定义:
public static void exchange(ref int a, ref int b)
{
int c = a;
a = b;
b = c;
}
函数调用:
int a = 10;
int b = 20;
exchange(ref a, ref b);
Console.WriteLine(a);
Console.WriteLine(b);
此时两个数字的成功的进行了交换,因为添加了ref关键字,代表传递的是引用,而不是值;
即参数传递的是引用的时候,方法里面的值发生改变,调用的地方一起改变。
out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。
方案三:
函数定义:
public static void Exchange(int[] arr)
{
int c = arr[0];
arr[0] = arr[1];
arr[1] = c;
}
函数调用:
int[] arr = new int[2] { 11,22 };
Exchange(arr);
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
此时两个数字的成功的进行了交换,说明数组名作为参数传递的时候,也是传递的引用。
五、可变参数的传递
可变参数在方法中被当作数组来处理
函数定义:
static int Sum(params int[] arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum = sum + arr[i];
}
return sum;
}
函数调用:
Console.WriteLine(Sum(1,2,3,4,5));
在main方法中对Sum的调用,可以随意传递任意数量的整数。
网友评论