in型参数
int 型参数通过值传递的方式将数值传入方法中,即我们在Java中常见的方法。
ref型参数
该种类型的参数传递变量地址给方法(引用传递),传递前变量必须初始化。
该类型与out型的区别在与:
1).ref 型传递变量前,变量必须初始化,否则编译器会报错, 而 out 型则不需要初始化
2).ref 型传递变量,数值可以传入方法中,而 out 型无法将数据传入方法中。换而言之,ref 型有进有出,out 型只出不进。
out 型参数
与 ref 型类似,仅用于传回结果。
注意:
1). out型数据在方法中必须要赋值,否则编译器会报错。
eg:如下图若将代码中的sum1方法的方法体
改为 a+=b; 则编译器会报错。原因:out 型只出不进,在没给 a 赋值前是不能使用的
改为 b+=b+2; 编译器也会报错。原因:out 型数据在方法中必须要赋值。
2). 重载方法时若两个方法的区别仅限于一个参数类型为ref 另一个方法中为out,编译器会报错
1 值传递 值传递对实参的值无任何影响
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)
{
int temp;
temp = x; /* 保存 x 的值 */
x = y; /* 把 y 赋值给 x */
y = temp; /* 把 temp 赋值给 y */
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 100;
int b = 200;
Console.WriteLine("在交换之前,a 的值: {0}", a);//输出100
Console.WriteLine("在交换之前,b 的值: {0}", b);//输出200
/* 调用函数来交换值 */
n.swap(a, b);
Console.WriteLine("在交换之后,a 的值: {0}", a);//输出100
Console.WriteLine("在交换之后,b 的值: {0}", b);//输出200 前后不变
Console.ReadLine();
}
}
}
2引用传递 对实参也会做出改变 ref来定义
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;
temp = x; /* 保存 x 的值 */
x = y; /* 把 y 赋值给 x */
y = temp; /* 把 temp 赋值给 y */
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 100;
int b = 200;
Console.WriteLine("在交换之前,a 的值: {0}", a);//100
Console.WriteLine("在交换之前,b 的值: {0}", b);//200
/* 调用函数来交换值 */
n.swap(ref a, ref b);
Console.WriteLine("在交换之后,a 的值: {0}", a);//200
Console.WriteLine("在交换之后,b 的值: {0}", b);//100
Console.ReadLine();
}
}
}
3 按输出传递参数 会改变实参 用out关键字来表示 可以输出多个返回值 使用前必须赋值
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void getValue(out int x )
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 100;
Console.WriteLine("在方法调用之前,a 的值: {0}", a);//原来的值为100
/* 调用函数来获取值 */
n.getValue(out a);
Console.WriteLine("在方法调用之后,a 的值: {0}", a);//调用方法后的值为5
Console.ReadLine();
}
}
}