ref和out的区别,以及params的作用

2个都是函数调用中的参数引用传递,ref和out的区别如下

1)ref的参数必须在传递之前进行初始化,也就是说,一定要先分配一个内存地址,而out不需要。(这点上来说,从字面上来看也能看出点大致来,ref引用,没分配内存的话,去哪引用呀)

2)在函数调用里面,out引用的一定要初始化,也就是说一定要有内存分配,而ref因为在调用之前就已经有了。那就不用了。

3)ref传递的参数在函数内部能直接使用,而out不可(这点是别的地方看到的,具体原因应该同上吧)

params的作用,就是可变函数参数。使用见下

// cs_params.cs
using System;
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
static void Main()
{
UseParams(1, 2, 3);
UseParams2(1, 'a', "test");
// An array of objects can also be passed, as long as
// the array type matches the method being called.
int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}

输出

 
1
            2
            3
            1
            a
            test
            10
            11
            12
以上示例选自msdn2005(就是vs2005所带的那个msdn)
原文地址:https://www.cnblogs.com/ziling8163/p/1401230.html