给你个代码看看吧。刚刚写的。希望你看了能有所了解。在控制台下看看输出结果你就知道了。
using System;
using System.Collections;
public class MyClass
{
public static void Main()
{
//code goes here;
int i=1,j=2;
int a=1,s=2;
int x1=1,y1=2;
Console.WriteLine("Before use Out!");
Console.WriteLine("x1={0},y1={1}",x1,y1);
Swap(ref i,ref j);
Swap1(a,s);
Swap2(out x1,out y1);
Console.WriteLine("after use out!");
Console.WriteLine("x1={0},y1={1}",x1,y1);
Console.WriteLine("a={0},s={1}",a,s);
Console.WriteLine("after use ref!");
Console.WriteLine("i={0},j={1}",i,j);
RL();
}
//static void Swap1(int a,int s)
static void Swap1(int a , int s)
{
int temp=a;
a=s;
s=temp;
}
static void Swap(ref int x,ref int y)
{
int temp=x;
x=y;
y=temp;
}
static void Swap2(out int x1,out int y1)
{
x1=3;
y1=4;
}
}
传递到 ref 参数的参数必须最先初始化。将此方法与 out 参数相比,后者的参数在传递到 out 参数之前不必显式初始化。
属性不是变量,不能作为 ref 参数传递。
如果两种方法的声明仅在它们对 ref 的使用方面不同,则将出现重载。但是,无法定义仅在 ref 和 out 方面不同的重载。例如,以下重载声明是有效的:
class MyClass
{
public void MyMethod(int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}
但以下重载声明是无效的:
class MyClass
{
public void MyMethod(out int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}
有关传递数组的信息,请参见使用 ref 和 out 传递数组。
示例
// cs_ref.cs
using System;
public class MyClass
{
public static void TestRef(ref char i)
{
// The value of i will be changed in the calling method
i = 'b';
}
public static void TestNoRef(char i)
{
// The value of i will be unchanged in the calling method
i = 'c';
}
// This method passes a variable as a ref parameter; the value of the
// variable is changed after control passes back to this method.
// The same variable is passed as a value parameter; the value of the
// variable is unchanged after control is passed back to this method.
public static void Main()
{
char i = 'a'; // variable must be initialized
TestRef(ref i); // the arg must be passed as ref
Console.WriteLine(i);
TestNoRef(i);
Console.WriteLine(i);
}
}
输出
b
b
[摘自MSDN]