方法参数关键字params、ref及out
???? public static void UseParams(params object[] list)
??????? {
??????????? for (int i = 0; i < list.Length; i++)
??????????? {
??????????????? Console.WriteLine(list[i]);
??????????? }
??????? }
??????? static void Main(string[] args)
??????? {
??????????? UseParams ('a', "aa","3");
??????????? UseParams ('b', "shit");
??????????? UseParams ("ok");
??????????? Console.Read();
??????? }
?? ?????public static void UseRef(ref int i)
??????? {
??????????? i += 100;
??????????? Console.WriteLine("i = {0}", i);
??????? }
??????? static void Main(string[] args)
??????? {
??????????? 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
1、若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
2、传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。
3、属性不是变量,因此不能作为 ref 参数传递。
4、尽管 ref 和 out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的。如果尝试这么做,将导致不能编译该代码。
5、如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载。
public static void UseOut(out int i)
??????? {
??????????? i = 10;
??????????? i += 100;
??????????? Console.WriteLine("i = {0}", i);
??????? }
??????? static void Main(string[] args)
??????? {
??????????? int i;
??????????? UseOut(out i);
??????????? Console.WriteLine("After the method calling: i = {0}", i);
??????????? Console.Read();
??????? }
通过上面发现out与ref十分相似,不同之处在于:
??????? 1、ref 要求变量必须在传递之前进行初始化。
2、尽管作为 out 参数传递的变量不需要在传递之前进行初始化,但需要调用方法以便在方法返回之前赋值。
?????
?
?
?