C# 初识Ref和Out

首先:两者都是按地址传递的,使用后都将改变原来参数的数值。

其次:ref可以把参数的数值传递进函数,但是out是要把参数清空,就是说你无法把一个数值从out传递进去的,out进去后,参数的数值为空,所以你必须初始化一次。这个就是两个的区别,或者说就像有的网友说的,ref是有进有出,out是只出不进。

ref(C# 参考)

ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。我们先看下普通的传参:
一、普通方法
int n1 = 5;
MyFun(n1);
Console.WriteLine(n1);

public static void MyFun(int i)
{
   i = i + 5;
}

毫无疑问调用输出:5

二、带ref参数的方法

public static void MyRef(ref int i)
 {
   i = i + 5;
 }

Static Void Main()

 {

    int n2 = 5;

    //int n2; //该变量为初始化直接使用ref传参是错误的
    MyRef(ref n2);
    Console.WriteLine(n2);

 }

这次输出是什么呢?结果是10,因为你ref是引用传值,直接改变n2的值.

out(C# 参考)

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

public static void MyOut(out int i)
 {
         i = 5 + 5;
 }

int n3 = 5;
 MyOut(out n3);
 Console.WriteLine(n3);

结果输出:10

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

四、带params参数的方法
 params 参数对应的是一个一维数组: int、string等
 在方法的参数列表中只能有一个params 参数
 当有多个参数时,params 参数必须放在参数列表的最后
 public static void MyParams(string str, params int[] arr)
 {

foreach (int n in arr)
    {
       Console.WriteLine(n);
    }
 }

MyParams("xg", 11, 22);

输出结果:11,22

using System;
using System.Collections.Generic;
using System.Text; namespace Test
{
class Class1
{
static void Main(string[] args)
{
int n1 = ;
MyFun(n1); //一、普通方法
Console.WriteLine(n1); int n2 = ;
MyRef(ref n2); //二、带ref参数的方法
Console.WriteLine(n2); int n3 = ;
MyOut(out n3); //三、带out参数的方法
Console.WriteLine(n3); MyParams("xg", , ); //四、带params参数的方法
MyParams("xg", , , , ); int number=;
Modify(ref number);
Console.WriteLine(number); int number1;
TestOut(out number1);
Console.WriteLine(number1); Console.ReadLine();
}
//一、普通方法
public static void MyFun(int i)
{
i = i + ;
}
//二、带ref参数的方法
public static void MyRef(ref int i)
{
i = i + ;
}
//三、带out参数的方法
public static void MyOut(out int i)
{
i = + ;
} //四、带params参数的方法
// params 参数对应的是一个一维数组: int、string等
// 在方法的参数列表中只能有一个params 参数
// 当有多个参数时,params 参数必须放在参数列表的最后
public static void MyParams(string str, params int[] arr)
{
foreach (int n in arr)
{
Console.WriteLine(n);
}
}
public static void Modify(ref int number)
{
number = ;
}
public static void TestOut(out int i)
{
i = ;
}
}
}
上一篇:用dbforge调试procedure


下一篇:css的再深入6(更新中···)