方法的参数:
形参和实参:
形参:全称为"形式参数"是在定义函数名和函数体的时候使用的参数,目的是用来接收调用该函数时传如的参数
实参:全称为"实际参数"是在调用时传递个该函数的参数.
编写程序,将主方法中的两个变量的值传递给swap方法中的两个形参,交换两个形参的值
namespace 方法的参数
{
class Program
{
static void wamp(int x,int y) //形参
{
int z;
z = x;
x = y;
y = z;
Console.WriteLine("x=" + x + "y=" + y);
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
wamp(a, b); //实参
Console.WriteLine("a=" + a + "b=" + b); //将a,b,赋值给x,y,但是a,b,本身不变
}
}
}
运行结果:
参数类型:
输出参数:
输出参数的调用:
namespace 方法的参数
{
class Program
{
static void square(int side,out int sq) //输出参数
{
sq = side * side;
}
static void Main(string[] args)
{
int c = 10;
int s;
square(c, out s); //输出参数赋值 ,加out
Console.WriteLine("s=" + s);
}
}
}
运行结果:
引用参数:
改变形参,实参也会改变
在例一上把形参实参前加上ref:
namespace 参数
{
class Program
{
static void swap(ref int x,ref int y)
{
int z;
z = x;
x = y;
y = z;
Console.WriteLine("x=" + x + "y=" + y);
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
swap(ref a, ref b);
Console.WriteLine("a=" + a + "b=" + b);
}
}
}
运行结果:
数组参数:
注:
foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用
foreach语句的一般语法格式如下:
foreach(数据类型 标识符 in 表达式)
{
循环体2
}
namespace 参数
{
class Program
{
static void CaleSquere(params int[] s)
{
foreach(int g in s)
{
int radius = g;
int square = radius * radius;
Console.WriteLine("squre=" + square);
}
}
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4 };
CaleSquere(arr);
}
}
}
方法重载:
方法重载即函数名重载,支持多个不同方法使用同一个方法名
要求:
namespace 重载
{
class Program
{
static int sum(int a,int b)
{
return a + b;
}
static int sum(int a,int b,int c)
{
return a + b + c;
}
static double sum(double a,double b)
{
return a + b;
}
static void Main(string[] args)
{
Console.WriteLine(sum(1, 2));
Console.WriteLine(sum(1, 2, 3));
Console.WriteLine(sum(2.5, 3.8));
}
}
}
运行结果:
田馥甄的《夏夜晚风live》,很喜欢的现场hhh
方法递归:
用递归实现1+2+3+4+.......+100:
namespace 递归
{
class Program
{
static int Fun(int i)
{
if (i == 1) //不用{}符号
return i;
return i + Fun(i - 1);
}
static void Main(string[] args)
{
int sum1 = Fun(100);
Console.WriteLine(sum1);
}
}
}