c#中params關鍵字應用【轉載要點、翻譯示例】

params 是C#開發語言中關鍵字, params主要的用處是在給函數傳參數的時候用,就是當函數的參數不固定的時候。 在方法聲明中的 params 關鍵字之後不允許任何其他參數,並且在方法聲明中只允許一個 params 關鍵字。 關於參數數組,需掌握以下幾點:

(1)若形參表中含一個參數數組,則該參數數組必須位於形參列表的最後;   

(2)參數數組必須是一維數組;   

(3)不允許將params修飾符與ref和out修飾符組合起來使用;   

(4)與參數數組對應的實參可以是同一類型的數組名,也可以是任意多個與該數組的元素屬於同一類型的變量;   

(5)若實參是數組則按引用傳遞,若實參是變量或表達式則按值傳遞。   

(6)可以不發送參數。 如果未發送任何參數,則params列表的長度爲零

用法:可變的方法參數,也稱數組型參數,適合於方法的參數個數不知的情況,用於傳遞大量的數組集合參數;當使用數組參數時,可通過使用params關鍵字在形參表中指定多種方法參數,並在方法的參數表中指定一個數組。示例如下:

public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

    public static void UseParams2(params object[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

    static void Main()
    {
        // You can send a comma-separated list of arguments of the 
        // specified type.可以傳遞指定類型的參數,用逗號分隔
        UseParams(1, 2, 3, 4);
        UseParams2(1, 'a', "test");

        // A params parameter accepts zero or more arguments.
	//可接受>=0個參數
        // The following calling statement displays only a blank line.
	//如下代碼是0個參數,會輸出一個空行
        UseParams2();

        // An array argument can be passed, as long as the array
        // type matches the parameter type of the method being called.
	//同樣也可傳遞一個數組,只要實參和形參的類型相符即可。
 	int[] myIntArray = { 5, 6, 7, 8, 9 }; 
	UseParams(myIntArray); 
	object[] myObjArray = { 2, 'b', "test", "again" }; 
	UseParams2(myObjArray); 
	// The following call causes a compiler error because the object 
	// array cannot be converted into an integer array.
	//如下代碼會報錯,因爲無法將myObjArray轉換爲整數數組
        //UseParams(myObjArray);

        // The following call does not cause an error, but the entire 
        // integer array becomes the first element of the params array.
	//如下代碼不會報錯,但是整個整數數組會變成參數數組,顯示爲System.Int32[]
        UseParams2(myIntArray);
    }
}
/*
Output:
    1 2 3 4
    1 a test
           
    5 6 7 8 9
    2 b test again
    System.Int32[]
*/





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章