当希望方法返回多个值时,声明 out 方法非常有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有一个以上的 out 参数。
若要使用 out 参数,必须将参数作为 out 参数显式传递到方法。out 参数的值不会传递到 out 参数。
不必初始化作为 out 参数传递的变量。然而,必须在方法返回之前为 out 参数赋值。
属性不是变量,不能作为 out 参数传递。
方法参数上的 ref 方法参数关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。
若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法。ref 参数的值被传递到 ref 参数。
传递到 ref 参数的参数必须最先初始化。将此方法与 out 参数相比,后者的参数在传递到 out 参数之前不必显式初始化。
属性不是变量,不能作为 ref 参数传递。
//上面的理解起来非常不好理解。下面我说说我自己的看法。
首先:两者都是按地址传递的,使用后都将改变原来的数值。很多人在论坛上解释说out是按数值传递,是错误的。简单的测试后可以知道out使用也能改变数值的,所以肯定是按照地址传递的。
其次:rel可以把参数的数值传递进函数,但是out是要把参数清空,就是说你无法把一个数值从out传递进去的,out进去后,参数的数值为空,所以你必须初始化一次。这个就是两个的区别,或者说就像有的网友说的,rel是有进有出,out是只出不进。经典!!!
小结:
ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。
使用ref前必须对变量赋值,out不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
区别可以参看下面的代码:
代码①
using System;
class TestApp
{
static void outTest(out int x, out int y)
{//离开这个函数前,必须对x和y赋值,否则会报错。
//y = x;
//上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
x = 1;
y = 2;
}
static void refTest(ref int x, ref int y)
{
x = 1;
y = x;
}
public static void Main()
{
//out test
int a, b;
//out使用前,变量可以不赋值
outTest(out a, out b);
Console.WriteLine("a={0};b={1}", a, b);
int c = 11, d = 22;
outTest(out c, out d);
Console.WriteLine("c={0};d={1}", c, d);
//ref test
int m, n;
//refTest(ref m, ref n);
//上面这行会出错,ref使用前,变量必须赋值
int o = 11, p = 22;
refTest(ref o, ref p);
Console.WriteLine("o={0};p={1}", o, p);
}
}
代码②
static void Main(string[] args)
{
int a = 0;
int b = 1;
Swap(ref a, ref b);
Console.WriteLine("a={0},b={1}",a,b);
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
代码③
public static class Test
{
public static void Test1(ref int t)
{
Console.Write(t);
t = 200;
Console.WriteLine(t);
}
public staticvoid Test2(out int t)
{
t = 100;
}
}
public class Program
{
static void Main()
{
int t1 = 100;
Test.Test1(ref t1);
Console.WriteLine(t1);
int t2 ;
Test.Test2(out t2);
Console.WriteLine(t2);
}
}
代码④
static void Main(string[] args)
{
int[] arr = { 5,3,8,1,6,9,4};
int max;
int min;
MaxMin(arr, out max,out min);
Console.WriteLine("max={0},min={1}", max, min);
}
static void MaxMin(int[] arr, out int max, out int min)
{
max = min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
}