params 關鍵字可以指定在參數數目可變處采用參數的方法參數。
在方法聲明中的 params 關鍵字之后不允許任何其他參數,并且在方法聲明中只允許一個 params 關鍵字。
示例
// cs_params.cs
using System;
public class MyClass
{
public static void UseParams(params int[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list[i]);
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list[i]);
Console.WriteLine();
}
public static void Main()
{
UseParams(1, 2, 3);
UseParams2(1, 'a', "test");
int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}
輸出
1
2
3
1
a
test
10
11
12
===============================================
方法參數上的 out 方法參數關鍵字使方法引用傳遞到方法的同一個變量。當控制傳遞回調用方法時,在方法中對參數所做的任何更改都將反映在該變量中。
當希望方法返回多個值時,聲明 out 方法非常有用。使用 out 參數的方法仍然可以返回一個值。一個方法可以有一個以上的 out 參數。
若要使用 out 參數,必須將參數作為 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。
不必初始化作為 out 參數傳遞的變量。然而,必須在方法返回之前為 out 參數賦值。
屬性不是變量,不能作為 out 參數傳遞。
如果兩個方法的聲明僅在 out 的使用方面不同,則會發生重載。不過,無法定義僅在 ref 和 out 方面不同的重載。例如,以下重載聲明是有效的:
class MyClass
{
public void MyMethod(int i) {i = 10;}
public void MyMethod(out 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_out.cs
using System;
public class MyClass
{
public static int TestOut(out char i)
{
i = 'b';
return -1;
}
public static void Main()
{
char i; // variable need not be initialized
Console.WriteLine(TestOut(out i));
Console.WriteLine(i);
}
}
輸出
-1
b
========================================
方法參數上的 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
新聞熱點
疑難解答