ref out 和没加这2个参数的区别
一、没加入参数例子
代码
using System;
class App
{
public static void UseRef( int i)
{
i += 100;
Console.WriteLine("i = {0}", i);
}
static void Main()
{
int i = 10;
// 查看调用方法之前的值
Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(i);
// 查看调用方法之后的值
Console.WriteLine("After the method calling: i = {0}", i);
Console.Read();
}
}
结果如下
Before the method calling: i = 10
i = 110
After the method calling: i = 10
class App
{
public static void UseRef( int i)
{
i += 100;
Console.WriteLine("i = {0}", i);
}
static void Main()
{
int i = 10;
// 查看调用方法之前的值
Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(i);
// 查看调用方法之后的值
Console.WriteLine("After the method calling: i = {0}", i);
Console.Read();
}
}
结果如下
Before the method calling: i = 10
i = 110
After the method calling: i = 10
二、ref参数
代码
using System;
class App
{
public static void UseRef(ref int i)
{
i += 100;
Console.WriteLine("i = {0}", i);
}
static void Main()
{
int i = 10;
// 查看调用方法之前的值
Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(ref i);
// 查看调用方法之后的值
Console.WriteLine("After the method calling: i = {0}", i);
Console.Read();
}
}
结果如下:
Before the method calling: i = 10
i = 110
After the method calling: i = 110
class App
{
public static void UseRef(ref int i)
{
i += 100;
Console.WriteLine("i = {0}", i);
}
static void Main()
{
int i = 10;
// 查看调用方法之前的值
Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(ref i);
// 查看调用方法之后的值
Console.WriteLine("After the method calling: i = {0}", i);
Console.Read();
}
}
结果如下:
Before the method calling: i = 10
i = 110
After the method calling: i = 110
三、out参数
代码
using System;
class App
{
public static void UseRef(out int i,int j)
{
i = 100;
Console.WriteLine("i+j = {0}", i+j);
}
static void Main()
{
int i;
// 查看调用方法之前的值
//Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(out i,1);
// 查看调用方法之后的值
Console.WriteLine("After the method calling: i = {0}", i);
Console.Read();
}
}
结果如下:
i+j = 101
After the method calling: i = 100
class App
{
public static void UseRef(out int i,int j)
{
i = 100;
Console.WriteLine("i+j = {0}", i+j);
}
static void Main()
{
int i;
// 查看调用方法之前的值
//Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(out i,1);
// 查看调用方法之后的值
Console.WriteLine("After the method calling: i = {0}", i);
Console.Read();
}
}
结果如下:
i+j = 101
After the method calling: i = 100