您现在的位置: 无忧电子商务网 >> 信息学院 >> 程序开发 >> asp.net >> 正文

c#中通过值和引用传递参数(downmoon)

作者:作者:未…    信息学院来源:网络收集    点击数:    更新时间:2006-8-28 我要参与讨论

   

c#中通过值和引用传递参数(downmoon)

在 C# 中,既可以通过值也可以通过引用传递参数。通过引用传递参数允许函数成员(方法、属性、索引器、运算符和构造函数)更改参数的值,并保持该更改。若要通过引用传递参数,请使用 ref 或 out 关键字。为简单起见,本主题的示例中只使用了 ref 关键字。有关 ref 和 out 之间的差异的信息,请参见、使用 ref 和 out 传递数组。

本主题包括下列章节:

  • 传递值类型参数
  • 传递引用类型参数

它还包括以下示例:

示例演示是否使用 ref 或 out1通过值传递值类型否2通过引用传递值类型是3交换值类型(两个整数)是4通过值传递引用类型否5通过引用传递引用类型是6交换引用类型(两个字符串)是

传递值类型参数

值类型变量直接包含其数据,这与引用类型变量不同,后者包含对其数据的引用。因此,向方法传递值类型变量意味着向方法传递变量的一个副本。方法内发生的对参数的更改对该变量中存储的原始数据无任何影响。如果希望所调用的方法更改参数值,必须使用 ref 或 out 关键字通过引用传递该参数。为了简单起见,以下示例使用 ref。

示例 1:通过值传递值类型

下面的示例演示通过值传递值类型参数。通过值将变量 myInt 传递给方法 SquareIt。方法内发生的任何更改对变量的原始值无任何影响。

// PassingParams1.cs 
using System;
class PassingValByVal
{
static void SquareIt(int x)
// The parameter x is passed by value.
// Changes to x will not affect the original value of myInt.
{
x *= x;
Console.WriteLine("The value inside the method: {0}", x);
}
public static void Main()
{
int myInt = 5;
Console.WriteLine("The value before calling the method: {0}",
myInt);
SquareIt(myInt); // Passing myInt by value.
Console.WriteLine("The value after calling the method: {0}",
myInt);
}
}

输出

The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 5

代码讨论

变量 myInt 为值类型,包含其数据(值 5)。当调用 SquareIt 时,myInt 的内容被复制到参数 x 中,在方法内将该参数求平方。但在 Main 中,myInt 的值在调用 SquareIt 方法之前和之后是相同的。实际上,方法内发生的更改只影响局部变量 x。

示例 2:通过引用传递值类型

下面的示例除使用 ref 关键字传递参数以外,其余与“示例 1”相同。参数的值在调用方法后发生更改。

// PassingParams2.cs 
using System;
class PassingValByRef
{
static void SquareIt(ref int x)
// The parameter x is passed by reference.
// Changes to x will affect the original value of myInt.
{
x *= x;
Console.WriteLine("The value inside the method: {0}", x);
}
public static void Main()
{
int myInt = 5;
Console.WriteLine("The value before calling the method: {0}",
myInt);
SquareIt(ref myInt); // Passing myInt by reference.
Console.WriteLine("The value after calling the method: {0}",
myInt);
}
}

输出

The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25

代码讨论

本示例中,传递的不是 myInt 的值,而是对 myInt 的引用。参数 x 不是 int 类型,它是对 int 的引用(本例中为对 myInt 的引用)。因此,当在方法内对 x 求平方时,实际被求平方的是 x 所引用的项:myInt。

示例 3:交换值类型

更改所传递参数的值的常见示例是 Swap 方法,在该方法中传递 x 和 y 两个变量,然后使方法交换它们的内容。必须通过引用向 Swap 方法传递参数;否则,方法内所处理的将是参数的本地副本。以下是使用引用参数的 Swap 方法的示例:

[1] [2] [3] 下一页

在google里搜索更多c#中通过值和引用传递参数(downmoon)

Google
Web www.51ec.org
【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
我来说两句 对此文章发表了评论
  昵 称: *必填    ·注册用户·
  评 分: 1分 2分 3分 4分 5分     严禁发表危害国家安全、政治、黄色淫秽等内容的评论,用户需对自己在使用本网站服务过程中的行为承担法律责任。本站管理员有权保留或删除评论内容,评论内容只代表机友个人观点,与本网站立场无关。  
评 论
内 容

 
评论列表 (最新 评论仅限网友观点!)

供求信息




| 设为首页 | 加入收藏 | 关于我们 | 广告服务 | 联系方式 | 友情链接 | 版权申明