static void swap(ref int i1,ref int i2)
{
int temp = i1;
i1 = i2;
i2 = temp;
}
//使用时,通过ref声明为引用。
int i1 = 10, i2 = 20;
swap(ref i1, ref i2);
Console.WriteLine("i1={0},i2={1}", i1, i2);
1.
static void IncAge(int age) //复制了age,函数内部改变的是age的副本
{
age++;
}
2.
ref用于内部对外部的值进行改变。
//ref用于内部对外部的值进行改变。
static void IncAge( ref int refage) //ref把age声明为一个引用,age必须先初始化
{
refage++;
}
3.
out用于内部对外部变量进行赋值,一般应用于函数有多个返回值的场景。
static void IncAge(out int outage)
{
outage = 30;
}
int outage; //不需要初始化,初始化也不起作用
String str = Console.ReadLine();
if (int.TryParse(str, out outage))
{
Console.WriteLine("转换成功,{0}", outage);
}
else
{
Console.WriteLine("转换失败,{0}", outage);
}