params 关键字可以指定在参数数目可变处采用参数的方法参数。
示例:
字面意思比较难懂,所以看示例很有用。
// keywords_params.cs using System; class App { public static void UseParams(params object[] list) { for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } static void Main() { // 一般做法是先构造一个对象数组,然后将此数组作为方法的参数 object[] arr = new object[3] { 100, 'a', "keywords" }; UseParams(arr); // 而使用了params修饰方法参数后,我们可以直接使用一组对象作为参数 // 当然这组参数需要符合调用的方法对参数的要求 UseParams(100, 'a', "keywords"); Console.Read(); } }
ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。
按引用传递值类型是有用的,但是 ref 对于传递引用类型也是很有用的。这允许被调用的方法修改该引用所引用的对象,因为引用本身是按引用来传递的。
// keywords_ref.cs using System; class App { public static void UseRef(ref int i) { i += 100; Console.WriteLine("i = {0}", i); } static void Main() { int i = 10; // 查看调用方法之前的值 Console.WriteLine("Before the method calling: i = {0}", i); UseRef(ref i); // 查看调用方法之后的值 Console.WriteLine("After the method calling: i = {0}", i); Console.Read(); } } /**//* 控制台输出: Before the method calling : i = 10 i = 110 After the method calling: i = 110 */
out 关键字会导致参数通过引用来传递。这与 ref 关键字类似。
与 ref 的不同之处:
与 ref 示例不同的地方只要将 ref 改为 out,然后变量 i 仅需要声明即可。
static void Main() { //int i = 10; 改为 int i; // }