码迷,mamicode.com
首页 > 其他好文 > 详细

ref in out params

时间:2015-04-13 00:01:06      阅读:391      评论:0      收藏:0      [点我收藏+]

标签:

参数类型可以分为ref、in、out这三种,默认的都是in。

通过引用传递参数, 可使用ref或out关键字。ref和out这两个关键字都能够提供相似的功效,其作用也很像C中的指针变量。它们的区别是:

1、把未赋值的变量用作ref参数是非法的,但可以把未赋值的变量用作out参数。在函数使用out参数时,必须把它看成是尚未赋值,调用代码可以把已赋值的变量用作out参数,但存储在该变量中的值会在函数执行时丢失。

以下是关于out使用的一个示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ch5t05
{
    class Program
    {
        static int MaxValue(int[] intArray, out int maxIndex)
        { 
            int maxVal=intArray[0];
            maxIndex = 0;
            for (int i = 1; i < intArray.Length; i++)
            {
                if (intArray[i] > maxVal)
                { 
                    maxVal=intArray[i];
                    maxIndex = i;
                }
            }
            return maxVal;
        }
        static void Main(string[] args)
        {
            int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
            int maxIndex;
            Console.WriteLine("The maxium value in myArray is {0}",MaxValue(myArray,out maxIndex));
            Console.WriteLine("The first occurance of this value is at element{0}",maxIndex+1);
            Console.ReadKey();
        }
    }
}

 

2、使用ref和out时,在方法的参数和执行方法时,都要加Ref或Out关键字。以满足匹配。

3、out适合用在需要retrun多个返回值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。不必初始化作为 out 参数传递的变量。但必须在方法返回之前为 out 参数赋值。

 

 

params:

一个函数中只能一个参数带params关键字;带params关键字的参数必须是最后一个参数;带params关键字的参数必须是一维数组。在调用的时候可以不给他传值,也可以给他传值,还可以给他传多个值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ch0501
{
    class Program
    {
        static string test(String name,params String[] words)
        {
            String msg=name;
            foreach(String word in words)
            {
                msg+=word;
            }
            return msg;
        }
        static void Main(string[] args)
        {
            Console.WriteLine(test("liming"," how are you"));
            Console.WriteLine(test("lili", " a girl", " a boy"));
            Console.WriteLine(test("shasha"));
            Console.ReadKey();
        }
    }
}

 

ref in out params

标签:

原文地址:http://www.cnblogs.com/lurongrong/p/4420896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!