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

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

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

  rst element is: -3

代码讨论

方法内发生的所有更改都影响 Main 中的原始数组。实际上,使用 new 运算符对原始数组进行了重新分配。因此,调用 Change 方法后,对 myArray 的任何引用都将指向 Change 方法中创建的五个元素的数组。

示例 6:交换两个字符串

交换字符串是通过引用传递引用类型参数的很好的示例。本示例中,str1 和 str2 两个字符串在 Main 中初始化,并作为由 ref 关键字修饰的参数传递给 SwapStrings 方法。这两个字符串在该方法内以及 Main 内均进行交换。

// PassingParams6.cs
using System;
class SwappinStrings
{
static void SwapStrings(ref string s1, ref string s2)
// The string parameter x is passed by reference.
// Any changes on parameters will affect the original variables.
{
string temp = s1;
s1 = s2;
s2 = temp;
Console.WriteLine("Inside the method: {0}, {1}", s1, s2);
}
public static void Main()
{
string str1 = "John";
string str2 = "Smith";
Console.WriteLine("Inside Main, before swapping: {0} {1}",
str1, str2);
SwapStrings(ref str1, ref str2); // Passing strings by reference
Console.WriteLine("Inside Main, after swapping: {0}, {1}",
str1, str2);
}
}

输出

Inside Main, before swapping: John Smith
Inside the method: Smith, John
Inside Main, after swapping: Smith, John

代码讨论

本示例中,需要通过引用传递参数以影响调用程序中的变量。如果同时从方法头和方法调用中移除 ref 关键字,则调用程序中不会发生任何更改。

 

上一页  [1] [2] [3] 

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

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

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

供求信息




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