日期:2014-05-17  浏览次数:21093 次

请教C#中ref与out的用法
如题,在C#中ref与out应该怎么用,什么时候要用到这两个关键字,请各位大哥们教教我

------解决方案--------------------
ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:

class RefOutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}

 
按引用传递值类型(如本主题前面所示)是有用的,但是 ref 对于传递引用类型也是很有用的。这允许被调用的方法修改该引用所引用的对象,因为引用本身是按引用来传递的。下面的示例显示出当引用类型作为 ref 参数传递时,可以更改对象本身。

class RefRefExample
{
static void Method(ref string s)
{
s = "changed";
}
static void Main()
{
string str = "original";
Method(ref str);
// str is now "changed"
}
}

 

参数传递可分值传递,引用传递。 
引用类型都是引用传递,就是对传递进去的变量的修改会反映在原来的变量上, 
值类型 当不用 out或者 ref的时候就是 值传递,就是对传递进去的变量的修改不会反映在原来的变量上,修改的只是原来变量的一个副本。 
加上 out或者 ref可以实现值类型的引用传递
 

out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。例如:

class CS0663_Example 
{
// Compiler error CS0663: "Cannot define overloaded 
// methods that differ only on ref and out".
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}
 

尽管作为 out 参数传递的变量不必在传递之前进行初始化,但需要调用方法以便在方法返回之前赋值。

ref 和 out 关键字在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:

class CS0663_Example 
{
// Compiler error CS0663: "Cannot define overloaded 
// methods that differ only on ref and out".
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}

 

但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:

class RefOutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(out int i) { }
}

ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:

class RefExample
{
static void Method(ref int i)
{
i = 44;
}
static void Main()
{
int val = 0;
Method(ref val);
// val is now 44
}
}

 

传递到 ref 参数的参数必须最先初始化。这与 out 不同,后者的参数在传递之前不需要显式初始化。尽管 ref 和 out 在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:

class CS0663_Example 
{
// Compiler error CS0663: "cannot define overloaded 
// methods that differ only on ref and out".
public void SampleMethod(ref int i) { }
public void SampleMethod(out int i) { }
}

 

但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两个参数,则可以进行重载,如下例所示:

class RefOutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}

------解决方案--------------------
这是ref的用法,ref起到引用传递的作用,你可以把ref去掉看看结果
C# code

        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 Tes