1、c#函数只能在某个类中定义,函数不能嵌套定义即在某个函数中定义其它函数。
函数由访问属性(public,private,protected,…);
是否是静态static;
返回值类型声明;
函数名称;
形式参数序列;
函数体
eg:
class A{
public static long fac(int n){
long f=1;
….
return f;
}
private bool isPrime(int n){
bool flag=true;
for(int i=2;i<n;i++)
if(n%i==0){
flag=false;break;
}
return flag;
}
}
2、函数调用:如果是静态函数,可以通过类名去直接调用;如果是非静态函数则需要通过类对象去调用。
eg:
class A{
public static void fun1(){…..}
public void fun2(){…}
}
class B{
public static void Main(string[] arg){
A.fun1();//因为fun1()是静态函数,在运行前已经分配入口地址,通过入口地址调用函数。
A.fun2();//错误的,没有在运行前分配入口地址。
非静态函数只有在对象创建后分配其入口地址。
A obj=new A();
obj.fun2();
}
}
3、形式参数与实际参数传递:
1) 值传递:基本值类型数据
static void swap(int x, int y)
{
int t = x; x = y; y = t;
}
2) 引用传递:
static void swap(int[] arr)
{
int t = arr[0]; arr[0] = arr[1]; arr[1] = t;
}
class Student
{
public string name;
}
class Ex1_1
{
static void changeName(Student s)
{
s.name = "zhangsan";
}
static void Main(string[] args)
{
Student s1 = new Student();
s1.name = "lisi";
changeName(s1);
Console.WriteLine(s1.name);
Console.ReadLine();
}
}
4、输出参数out
static void fun(int x1, int x2, out int x3)
{
x3 = x1 + x2;
}
static void Main(string[] args)
{
int x = 10, y = 100, z;
fun(x, y, out z);//接收输出参数值,不需要为z赋初始值
Console.WriteLine(x+" "+y+" "+z);
Console.ReadLine();
}
5、定义引用参数
static void swap(ref int x, ref int y)
{
int t = x; x = y; y = t;
}
static void Main(string[] args)
{
int m = 10, n = 100;
swap(ref m, ref n);//将传值类型转换成传引用。
Console.WriteLine(m+" "+n);
Console.ReadLine();
}
6、带有可变参数的函数
static int fun(int a,params int[] x)
{
int s = 0;
for (int i = 0; i < x.Length; i++)
s += x[i];
return s;
}
static void Main(string[] args)
{
Console.WriteLine(fun(1,2,3,4));
Console.WriteLine(fun(1));
Console.WriteLine(fun(1,3,4,4,6,7));
Console.ReadLine();
}
7、递归函数:函数递归调用
递归函数:1)递推公式,2)递归出口
static long fac(int n){
if(n==0||n==1)
return 1;
else
return n*fac(n-1);
}
汉诺塔程序:
A ,B,C
n=1: A-->C
n>1: 将A柱 n-1盘借助于C搬到B柱
将A柱最后盘搬到C
将B柱 n-1盘借助于A搬到C柱
static void disp(string a,string c)
{
Console.WriteLine("{0}--->{1}", a, c);
}
static void hannota(string a, string b, string c, int n)
{
if (n == 1)
disp(a, c);
else
{
hannota(a, c, b, n - 1);
disp(a, c);
hannota(b, a, c, n - 1);
}
}
本章练习题下载地址:点此下载