C#中的参数介绍

1.   值类型的参数                                                                                                                                                           

正常的参数语法格式

语法:参数类型参数名

Public void testCommand(int x)

{ 

}

2.   引用类型的参数

使用原因:

           当我们想通过函数改变函数外面的值,那么就将其地址传递进去。

语法:ref   参数类型    参数名

Example

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication3

{

    class Program

    {

        public void testInt(int x)

        {

            x = 1;

        }

        public void testRef(ref int x)

        {

            x = 2;

        }

        static void Main(string[] args)

        {

            int x = 0;

            Program p = new Program();

            p.testInt(x);

            Console.WriteLine("正常参数x=" + x);

            p.testRef(ref    x);

            Console.WriteLine("引用参数x=" + x);

        }

    }

}

 

运行结果:

正常参数x=0

                引用参数x=2

 

思考:

        函数参数加上ref,以及引用的时候加上ref,那么就相当于把地址传进去,那么修改了ref参数的值,那么就会改变原值,而没有ref的,那么就不会影响其值。

 

3.   输出参数

原因:有时方法计算的结果有多个,而return语句一次只能返回一个结果,这时候就要用到out关键字,使用out关键字表明该引用参数是用于输出的,而且调用该参数时不需要对参数进行初始化,

语法格式:

      out  参数类型    参数名

     

        example

       声明函数:

                 Class    program

{

   Public int  testOut(out x,out y)

                   {

                 x=1;

                 y=2

                 int z;

                 z=1+2;

                 return z;

}

}

调用函数

        int   x=0,y=0,z=0;

        program p=new program();

                 z=p.testOut(out x,out y);

运行的结果:

            X=1;y=2;z=1+2=3;

4.    数组型参数

原因:

      当需要传递的参数个数不确定时,如求几个数的和,由于没有规定是几个数,运行程序时,每次输入值的个数不一定一样。为了解决这个问题,c#语言采用params关键字来表明参数的个数是不确定的。

语法:

         Params 参数类型   参数名

注:参数类型必须是数组。

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication3

{

    class Program

    {

 

        public void testParam(params object[]  nums)

        {

            for(int i=0;i<nums.Length;i++)

            Console.WriteLine(nums[i]);

        }

 

        static void Main(string[] args)

        {

            int x = 0;

            int y = 0;

            int z = 0;

            Program p = new Program();

            p.testParam(x, y, z,3,4,"65",'c',"ddd");

            Console.ReadLine();

        }

    }

}

运行结果:

0

0

0

3

4

65

c

ddd

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值