您的位置:首页 > 编程语言 > C#

c#中ref和out的区别

2007-12-06 16:27 239 查看
方法参数上的 out 方法参数关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。
当希望方法返回多个值时,声明 out 方法非常有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有一个以上的 out 参数。
若要使用 out 参数,必须将参数作为 out 参数显式传递到方法。out 参数的值不会传递到 out 参数。
不必初始化作为 out 参数传递的变量。然而,必须在方法返回之前为 out 参数赋值。
属性不是变量,不能作为 out 参数传递。

方法参数上的 ref 方法参数关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。
若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法。ref 参数的值被传递到 ref 参数。
传递到 ref 参数的参数必须最先初始化。将此方法与 out 参数相比,后者的参数在传递到 out 参数之前不必显式初始化。
属性不是变量,不能作为 ref 参数传递。

也就是说ref类似于c语言中的指针。

using System;

class Account
{
private int balance = 0; //字段
public int Balance //属性
{
get { return balance; }
set { balance = value;}
}
public void Deposit(int n)
{ this.balance += n; }

public void WithDraw(int n)
{ this.balance -= n; }
}

class Client
{
public static void Main()
{
Account a = new Account();
a.Balance = 1000; // 可以读写属性,因为属性Balance是public型的
//a.balance = 1000; //不可以读写字段,因为字段balance是private型的

a.WithDraw(500);
a.Deposit(2000);
Console.WriteLine("before Method call: a.balance = {0}", a.Balance);

int x = 1;
int y = 100;
int z;
AMethod(x, ref a.balance ,out z); //ref a.balance 正确,a.balance是字段变量
//AMethod(x, ref a.Balance ,out z); //ref a.Balance 错误,a.Balance是属性
y = a.balance;
Console.WriteLine("After Method Call : x = {0}, y = {1}, z = {2}", x, y, a.balance);
AMethod(x, ref y ,out a.balance); //out a.balance 正确,a.balance是字段变量
//AMethod(x, ref y ,out a.Balance); //ref a.Balance 错误,a.Balance是字段变量
z = a.balance;
Console.WriteLine("After Method Call : x = {0}, y = {1}, z = {2}", x, y, a.balance);
AMethod(x, ref y ,out z);
Console.WriteLine("After Method Call : x = {0}, y = {1}, z = {2}", x, y, z);
}

public static void AMethod(int x, ref int y, out int z)
{
x = 7;
y = 8;
z = 9;
}
}

输出结果:

---------- C# Run ----------
before Method call: a.balance = 2500
After Method Call : x = 1, y = 8, z = 8
After Method Call : x = 1, y = 8, z = 9
After Method Call : x = 1, y = 8, z = 9

输出完成 (耗时: 0 秒) - 正常终止
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: