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 关键字,则调用程序中不会发生任何更改。
| 对此文章发表了评论 |

