2012-04-25 22:03:41|?次阅读|上传:wustguangh【已有?条评论】发表评论
交换字符串是通过引用传递引用类型参数的很好的示例。本示例中,str1 和 str2 两个字符串在 Main 中初始化,并作为由 ref 关键字修饰的参数传递给 SwapStrings 方法。这两个字符串在该方法内以及 Main 内均进行交换。
// PassingParams6.cs
using System;
class SwappinStrings {
// The string parameter x is passed by reference.
// Any changes on parameters will affect the original
//variables.
static void SwapStrings(ref string s1, ref string s2) {
string temp = s1;
s1 = s2;
s2 = temp;
Console.WriteLine("Inside the method: , ", s1, s2);
}
public static void Main() {
string str1 = "John";
string str2 = "Smith";
Console.WriteLine("Inside Main, before swapping: ",
str1, str2);
// Passing strings by reference
SwapStrings(ref str1, ref str2);
Console.WriteLine("Inside Main, after swapping: , ",
str1, str2);
}
}
Inside Main, before swapping: John Smith Inside the method: Smith, John Inside Main, after swapping: Smith, John
本示例中,需要通过引用传递参数以影响调用程序中的变量。如果同时从方法头和方法调用中移除 ref 关键字,则调用程序中不会发生任何更改。