可变参数、函数重载
当不确定形参的个数的时候,可以使用可变参数。
定义语法params + 数据类型[]+名称
public static void add(out int num1,params int[] array)
//当需要涉及另一个参数时,请放在可变参数之前。
{
num1 = 0; //赋初值,因为out的使用,num1已经“无效了”。
for (int i = 0; i < array.Length; i++)
{
num1+=array[i];
}
}
public static void Main(string[] arg)
{
int num;
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//另一种传参方式
//add(out num, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
add(out num, numbers);
Console.WriteLine($"这些数的和为{num}");
}
函数的重载::函数名相同但是参数列表不同(包括数据类型、参数数量、参数顺序)
public static int average(int a, int b)
{
return (a + b) / 2;
}
public static double average(double a, double b)
{
return (a + b) / 2;
}
public static void Main(string[] arg)
{
Console.WriteLine(average(2,4));
Console.WriteLine(average1(3.2,4.6));
}
如上,相同的函数名却有着不同的作用。
原文地址:https://blog.csdn.net/m0_69089705/article/details/142633230
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!