现在的位置: 首页 > 综合 > 正文

ref的作用 引用和值传递

2013年01月25日 ⁄ 综合 ⁄ 共 1403字 ⁄ 字号 评论关闭

写的简单实用,我稍修改了,拿给大家看。

先看一下示例

using System;

using System.Text;

using System.Collections.Generic;

namespace Example_5

{

class
Program1

{

///<summary>

///比较ab的大小并按由小到大的顺序排列ab

///</summary>

///<param name="a">整数a</param>

///<param name="b">整数b</param>

static
void Swap(int a,
int
b)

{

int c = 0;

if (a > b)

{

c = a;

a = b;

b = c;

}

}

static
void Main(String[] args)

{

int x = 6;

int y = 4;

Swap(x,y);

Console.WriteLine("x
的值为:{0},y的值为:{1}", x, y);

Console.ReadLine();

}

}

}

我们的本意是比较ab的大小并按由小到大的顺序排列ab,可是结果是

x 的值为:6,y的值为:4

并没有像我们所想的哪样,输出我们想要的结果.

分析

实际上,这是由于C#中这一类型的调用默认为值参数的调用既在使用参数时,将参数的值传给方法使用,而方法中对此值的改变并不影响方法的外部变量.所以没有得到我们想要的结果.

解决问题的方法是使用ref关键字.

ref关键字是使用参数按引用来传递的.其效果是方法中对参数所做的任何改变将功反映到变量中.

改进的程序

using System;

using System.Text;

using System.Collections.Generic;

namespace Example_5

{

class
Program1

{

///<summary>

///比较ab的大小并按由小到大的顺序排列ab

///</summary>

///<param name="a">整数a</param>

///<param name="b">整数b</param>

static
void Swap(ref
int a,ref
int b)

{

int c = 0;

if (a > b)

{

c = a;

a = b;

b = c;

}

}

static
void Main(String[] args)

{

int x = 6;

int y = 4;

Swap(ref x,ref
y);

Console.WriteLine("x
的值为:{0},y的值为:{1}", x, y);

Console.ReadLine();

}

}

}

运行结果为

4 6

说明

1.ref 关键字使参数按引用传递。

2.其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。

3.使用ref 参数,方法定义和调用方法都必须显式使用
ref 关键字

4.传递到
ref 参数的参数必须最先初始化。

5. 示例代码

using System;

using System.Text;

using System.Collections.Generic;

namespace Example_5

{

class
Program1

{

static
void ChangeName(ref
String ChangedName)

{

ChangedName =
"凤姐
";

}

static
void Main()

{

String OrginalName =
"你老婆";

ChangeName(ref OrginalName);

Console.WriteLine(OrginalName);

}

}

}

运行结果为:

凤姐

抱歉!评论已关闭.