c# 关键字 params ref out

3, params

params关键字可以指定在参数数目可变处采用参数的方法参数。

  1. 在方法声明中的 params 关键字之后不允许任何其他参数,并且在方法声明中只允许一个 params 关键字。

字面意思比较难懂,所以看示例很有用。

using System;

 

class App

{

    public static voidUseParams(params object[] list)

    {

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

        {

           Console.WriteLine(list[i]);

        }

    }

 

    static void Main()

    {

        // 一般做法是先构造一个对象数组,然后将此数组作为方法的参数

        object[] arr = newobject[3] { 100, 'a', "keywords" };

        UseParams(arr);

 

        // 而使用了params修饰方法参数后,我们可以直接使用一组对象作为参数

        // 当然这组参数需要符合调用的方法对参数的要求

        UseParams(100,'a', "keywords");

 

        Console.Read();

    }

}

 

关键字:refout

 

  1. 若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
  2. 传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。

// keywords_ref.cs

using System;

class App

{

    public static void UseRef(ref int i)

    {

        i += 100;

        Console.WriteLine("i = {0}",i);

    }

    static void Main()

    {

        int i = 10;

        // 查看调用方法之前的值

        Console.WriteLine("Before themethod calling: i = {0}", i);

        UseRef(ref i);

        // 查看调用方法之后的值

        Console.WriteLine("After themethod calling: i = {0}", i);

        Console.Read();

    }

}

/*

控制台输出:

Beforethe method calling : i = 10

i = 110

Afterthe method calling: i = 110

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值