ref关键字使参数按引用传递。其效果是,当控制权传递回调方法时,在方法中对参数的任何更改都将反映在该变量中若要使用ref参数,则在定义方法和调用方法都必须显示使用ref关键字,

class RefExample

{

    static void Method(ref int i)

    {

        i = 44;

    }

    static void Main()

    {

        int val = 0;

        Method(ref val);

        // val is now 44

    }

}

 

ref在变量之前必须进行初始化。按引用传递值类型是有用的,但是ref对于应用类型也是很用用处的,这允许北条用的方法修改该引用的对像,因为应用本身是按引用来传递的

class RefRefExample

{

    static void Method(ref string s)

    {

        s = "changed";

    }

    static void Main()

    {

        string str = "original";

        Method(ref str);

        // str is now "changed"

    }

}

 

Out关键字会导致参数通过引用来传递,这与ref类似,不同于ref之处必须在传递之前进行初始化,方法定义和调用方法都必须显示使用out关键字。若要使用out参数,方法定义和调用方法都必须显示使用out关键字。

class OutExample

{

    static void Method(out int i)

    {

        i = 44;

    }

    static void Main()

    {

        int value;

        Method(out value);

        // value is now 44

    }

}

尽管作为out参数传递的变量不必在传递之前初始化,但需要调用方法返回之前赋值。在方法有多个返回值时,声明out方法很有用,使用out参数的方法任然可以将变量作为反复回类型来访问。

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;

    }

 

    Params 关键字可以指定在参数数目可变处采用参数的方法参数 ,只能为一个动态参数,可以决定不是动态参数的参数不能连续定义两个动态参数,params参数必须是一维数组

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();

    }

 

    static void Main()

    {

        UseParams(1, 2, 3);

        UseParams2(1, 'a', "test");

 

        // An array of objects can also be passed, as long as

        // the array type matches the method being called.

        int[] myarray = new int[3] {10,11,12};

        UseParams(myarray);

    }

}