方法又称成员函数(Member Function),集中体现了类或对象的行为。方法同样分为静态方法和实例方法。静态方法只可以操作静态域,而实例方法既可以操作实例域,也可以操作静态域--虽然这不被推荐,但在某些特殊的情况下会显得很有用。
方法也有如域一样的5种存取修饰符--public,protected,internal,protected internal,private,它们的意义如前所述。
方法的参数传递有四种类型:传值(by value),传址(by reference),输出参数(by output),数组参数(by array)。传值参数无需额外的修饰符,传址参数需要修饰符ref,输出参数需要修饰符out,数组参数需要修饰符params。
值传递和地址传递
using System;
class Test
{
static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
static void Swap(int x,int y)
{
int temp = x;
x = y;
y = temp;
}
static void Main()
{
int i = 1, j = 2;
Swap(ref i, ref j);
Console.WriteLine("i = {0}, j = {1}", i, j);
Swap(i,j);
Console.WriteLine("i = {0}, j = {1}", i, j);
}
}
程序经编译后执行输出:
i = 2, j = 1
i = 2, j = 1
数组传递
数组参数也是我们经常用到的一个地方--传递大量的数组集合参数。我们先看下面的例子:
using System;
class Test
{
static int Sum(params int[] args)
{
int s=0;
foreach(int n in args)
{
s+=n;
}
return s;
}
static void Main()
{
int[] var=new int[]{1,2,3,4,5};
Console.WriteLine("The Sum:"+Sum(var));
Console.WriteLine("The Sum:"+Sum(10,20,30,40,50));
}
}
程序经编译后执行输出:
The Sum:15
The Sum:150