C#參數默認是傳值的。
如果參數是值類型,那麼調用方法獲得的實參是值的副本,這樣在被調用的方法中更改實參值怎麼也影響不到調用者
的原始變量值。
而如果參數是Ref引用類型,那麼實參是有ref前綴的變量(不是值),這種情況下對其進行重新賦值就更改了原始變量
值(更改了引用[地址]所指向的數據)。
概括的說,我們能更改帶有ref前綴的變量的原始值,不帶ref前綴的變量更改不了原始值。
下面是一個例子:
public ValueRefExample()
{
this.InitializeComponent();
string first = "漩渦";
string second = "鳴人";
txblk1.Text = string.Format("初始值:First:{0},Second:{1}", first, second);
Swap(first, second);
txblk2.Text = string.Format("傳值方式交換值:First:{0},Second:{1}", first, second);
Swap(ref first, ref second);
txblk3.Text = string.Format("傳引用方式交換值:First:{0},Second:{1}", first, second);
string s1 = "宇智波";
string s2 = "佐助";
txblk4.Text = string.Format("初始值:S1:{0},S2:{1}", s1, s2);
Swap(ref s1, s2);
txblk5.Text = string.Format("傳值傳引用混合方式交換值:S1:{0},S2:{1}", s1, s2);
}
//傳值方式傳遞變量
static void Swap(string str1,string str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
//傳引用方式傳遞變量
static void Swap(ref string str1, ref string str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
//傳值傳引用混合傳遞變量
static void Swap(ref string str1,string str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
結果截圖: