2016年3月4日 星期五

C# 方法參數修飾詞 out ref params

C# in , out , ref , params


params 修飾詞

MSDN
當傳入array時可用,此時參數的數目不定
可傳入陣列
可傳入元素
可以什麼都不傳,此時陣列長度為0
在params之後不許有其他參數(params要放在最後一個參數)
且只能有一個params

//當有這樣一個陣列
Object[] ary = new object[3] { 300, 'x', "abc" };

//這個方法的參數宣告為params
private void TestFunc(params Object[] ary)
//我們可以直接傳入一組物件
TestFunc(200,'d',"xxx");

完整範例
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.
        // The following calling statement displays only a blank line.
        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.
        //UseParams(myObjArray);

        // The following call does not cause an error, but the entire 
        // integer array becomes the first element of the params array.
        UseParams2(myIntArray);
    }
}
/*
Output:
    1 2 3 4
    1 a test

    5 6 7 8 9
    2 b test again
    System.Int32[]
*/

ref 修飾詞

MSDN
把參數用傳參考的方式傳入函式
在宣告和呼叫的參數前都加上ref
參數在傳遞前一定要初始化
被傳入的參數,在函式被修改,也會改到他原本的值
屬性不能做為ref的參數

這樣子不構成重載,會報錯
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
這樣子可以
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }

out 修飾詞

MSDN
把參數用傳參考的方式傳入函式
參數在傳遞錢不一定要初始化
在宣告和呼叫的參數前都加上out
被傳入的參數,在函式被修改,也會改到他原本的值
函式可宣告多個out參數
在函式中一定要對out參數附值,否則報錯
直接在函式中修改out參數,就等於是回傳值

private void Test(out int a, out int b)
{
     a =3;
     b=5;
}
private void Call()
{
  int x=0;
  int y=4;
}
Test(out x, out y);

參數原本的值會被更動
class OutReturnExample
{
    static void Method(out int i, out string s1, out string s2)
    {
        i = 44;
        s1 = "I've been returned";
        s2 = null;
    }
    static void Main()
    {
        int value;
        string str1, str2;
        Method(out value, out str1, out str2);
        // value is now 44
        // str1 is now "I've been returned"
        // str2 is (still) null;
    }
}

int 修飾詞

傳入的參數不能被更動

沒有留言:

張貼留言