方法参数

来源:互联网 发布:成都网络综合布线 编辑:程序博客网 时间:2024/05/24 07:36

方法的形式参数

class MyMath{    public void Swap(int x, int y)    {                          int temp = x;        x = y;        y = temp;    }}

形式参数的类型为值类型

方法的实际参数

class MainClass{    public static void Main(string[] args)    {        MyMath mymt = new MyMath();        int myScore = 60;        int yourScore = 100;        mymt.Swap(myScore, yourScore);    }}

因为形式参数的类型为值类型,所以myScore的值并不会改变。

class MainClass{    public static void Main(string[] args)    {        MyMath mymt = new MyMath();        int myScore = 60;        int yourScore = 100;        mymt.Swap(myScore, yourScore);            //**myScore = 60**        Console.WriteLine(myScore);

引用参数

引用参数以ref修饰符声明

class MyMath{    public void Swap(ref int x,ref int y)        {            int temp = x;            x = y;            y = temp;        }}
class MainClass{    public static void Main(string[] args)    {        MyMath mymt = new MyMath();        int myScore = 60;        int yourScore = 100;        mymt.Swap(ref myScore, ref yourScore);            //**myScore = 100**        Console.WriteLine(myScore);    }}

ref修饰的变量在传递参数前一定要有初始值

输出参数

输出参数由out关键字标识

public void Cal(int a, int b, out int x, out int y){    x = a - b;    y = a + b;}

在方法中out修饰的参数必须先初始值,才能使用

public static void Main(string[] args){    MyMath mymt = new MyMath();    int numOne = 26;    int numTwo = 9;    int resultOne;    int resultTwo;    mymt.Cal(numOne, numTwo, out resultOne, out resultTwo);    Console.WriteLine("resultOne = " + resultOne);    // resultOne = 17    Console.WriteLine("resultTwo = " + resultTwo);    // resultTwo = 35}

out修饰的变量在传递前,可以没有初始值

数组参数

如果形参表中包含了数组型参数,那么它必须在参数表中位于最后,而且必须是一维数组类型。另外,数组型参数不可能将params修饰符与ref和out修饰符组合起来使用。

class MyMath{    public void Sum(params int[] a)    {        int result = 0;        foreach(int x in a)    {        result += x;    }        Console.WriteLine("结果为:" + result);    }}public static void Main(string[] args){    MyMath mymt = new MyMath();    mymt.Sum(1,2,3,4,5);}

这里的参数个数是任意个,甚至可以为0个

数组参数总结

参数的长度可变。长度可以为0。
只能使用一次,而且要放到最后。
后跟数组类型,不能跟ref、out一起搭配使用**

简单小结

  • 值参数:不附加任何修饰符。
  • 输出参数:以out修饰符声明,可返回一 个或多个值给调用者
  • 引用参数:以ref修饰符声明。
  • 数组参数:以params修饰符声明。
原创粉丝点击