方法: 函数完成某个功能的接口,一个方法只能实现一个功能,要保证功能单一。
方法结构:
public: 公共的,公开的
[public] static 返回值类型 方法名(参数列表)
{
// 方法体
}
方法的调用:
如果调用的方法跟被调用的的方法在同一个类中,可以省略被调用方法的类名,直接写方法。
类名.方法名(参数);
C#中没有全局变量这个东西:
用静态字段模拟
namespace ConsoleApplication1
{
class Program
{
public static int b = 90; //声明一个静态字段
static void Main(string[] args)
{
int a = 10;
Console.WriteLine("total:{0}", a + b);
int c = OrNum(); //调用方法
}
public static int OrNum()
{
int a = 19;
Console.WriteLine("total:{0}", a + b);
return 0;
}
}
}
C#可以返回数组:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] ret_array = OrNum(); //调用方法打印输出
for (int i = 0; i < ret_array.Length; i++)
{
Console.WriteLine("data:{0}", ret_array[i]);
}
}
public static int[] OrNum()
{
int[] array = new int[4];
for(int i = 0; i < array.Length; i++)
{
array[i] = i;
}
return array; //C#中可以返回数数组,C不行
}
}
}
out参数:
相当于C中的指针。区别在于不能传值下去,只能传值回来。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a, b, c, d;
OrNum(out a, out b, out c, out d); //相当于C中的&a &b &c &d,但是它不能传值下去,只能传值回来
Console.WriteLine("{0}, {1}, {2}, {3}", a, b, c, d);
}
public static void OrNum(out int a, out int b, out int c, out int d) //相当于C中的int* a, int* b, int* c, int* d
{
a = 1; //out参数必须赋值
b = 2;
c = 3;
d = 4;
}
}
}
ref参数:
既能传值下去,也能传值回来
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 0, b = 1, c = 2, d = 3;
OrNum(ref a, ref b, ref c, ref d); //调用方法传值下去,带改变后的数值回来
Console.WriteLine("{0}, {1}, {2}, {3}", a, b, c, d);
}
public static void OrNum(ref int a, ref int b, ref int c, ref int d)
{
a = b + c + d; //数据处理
}
}
}
params参数:
可变参类型,只能放在形参的最后一个类型前。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
OrNum("WangKing", 123, 1,2,3,4,5,6); //name:wangKing, id:123 array:1 2 3 4 5 6
}
public static void OrNum(string name, int id, params int[] array) //param必须放在最后一个形参前
{
Console.WriteLine("id:{0}, name:{1},", id ,name);
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i] );
}
Console.WriteLine();
}
}
}
方法的重载:
方法名相同,参数不同(类型,个数)的多个方法
一个有返回值,一个没有是不能构成重载。
递归:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
fucntion(0); //开始递归
}
public static void fucntion(int i)
{
if (i >= 10)
{
return; //大于10退出
}
Console.WriteLine("hello world");
i++;
fucntion(i); //自己调用自己
}
}
}