传值参数无需额外的修饰符,传址参数需要修饰符ref,输出参数需要修饰符out,数组参数需要修饰符params。传值参数在方法调用过程中如果改变了参数的值,那么传入方法的参数在方法调用完成以后并不因此而改变,而是保留原来传入时的值。传址参数恰恰相反,如果方法调用过程改变了参数的值,那么传入方法的参数在调用完成以后也随之改变。实际上从名称上我们可以清楚地看出两者的含义--传值参数传递的是调用参数的一份拷贝,而传址参数传递的是调用参数的内存地址,该参数在方法内外指向的是同一个存储位置。看下面的例子及其输出:
using System;
class Test
{
static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
static void Swap(int x,int y)
{
int temp = x;
x = y;
y = temp;
}
static void Main()
{
int i = 1, j = 2;
Swap(ref i, ref j);
Console.WriteLine("i = {0}, j = {1}", i, j);
Swap(i,j);
Console.WriteLine("i = {0}, j = {1}", i, j);
}
}
程序经编译后执行输出:
i = 2, j = 1
i = 2, j = 1
我们可以清楚地看到两个交换函数Swap()由于参数的差别--传值与传址,而得到不同的调用结果。注意传址参数的方法调用无论在声明时还是调用时都要加上ref修饰符。
using System;
class Test
{
static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
static void Swap(int x,int y)
{
int temp = x;
x = y;
y = temp;
}
static void Main()
{
int i = 1, j = 2;
Swap(ref i, ref j);
Console.WriteLine("i = {0}, j = {1}", i, j);
Swap(i,j);
Console.WriteLine("i = {0}, j = {1}", i, j);
}
}
程序经编译后执行输出:
i = 2, j = 1
i = 2, j = 1
我们可以清楚地看到两个交换函数Swap()由于参数的差别--传值与传址,而得到不同的调用结果。注意传址参数的方法调用无论在声明时还是调用时都要加上ref修饰符。
下面是两个相关帖,看看别人怎么讨论和分析这方面的问题,或许比单纯看书更好。http://expert.csdn.net/Expert/topic/2256/2256473.xml?temp=.894726
http://expert.csdn.net/Expert/topic/2268/2268067.xml?temp=.934704
C# 關鍵字 | 方法參數
方法參數中的 ref 方法參數關鍵字可使方法參考到傳遞至該方法的相同變數。此參數在方法中造成的任何變更將會在控制權傳遞回呼叫方法時反映至該變數。若要使用 ref 參數,此引數必須明確地以 ref 引數形式傳遞到方法中。ref 引數值將會傳遞給 ref 參數。傳遞給 ref 參數的引數必須先被初始化。將此點與 out 參數進行比較,可知其引數在傳遞至 out 參數之前並不一定要先明確地初始化。屬性並不是變數因此無法以 ref 參數傳遞。如果兩個方法的宣告僅在 ref 的使用方法不同時,就會產生多載。但是卻無法定義僅在 ref 和 out 有所不同的多載。舉例來說,下列多載宣告是有效的:class MyClass
{
public void MyMethod(int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}
但下列多載宣告是無效的:class MyClass
{
public void MyMethod(out int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}
如需傳遞陣列的詳細資訊,請參閱使用 ref 和 out 傳遞陣列。範例
// cs_ref.cs
using System;
public class MyClass
{
public static void TestRef(ref char i)
{
// The value of i will be changed in the calling method
i = 'b';
} public static void TestNoRef(char i)
{
// The value of i will be unchanged in the calling method
i = 'c';
} // This method passes a variable as a ref parameter; the value of the
// variable is changed after control passes back to this method.
// The same variable is passed as a value parameter; the value of the
// variable is unchanged after control is passed back to this method.
public static void Main()
{
char i = 'a'; // variable must be initialized
TestRef(ref i); // the arg must be passed as ref
Console.WriteLine(i);
TestNoRef(i);
Console.WriteLine(i);
}
}
輸出
b
b
請參閱
C# 關鍵字 | 方法參數