public partial class Form1 : Form ...{ public static void UseParams(params int[] list) ...{ string temp = ""; for (int i = 0; i < list.Length; i++) temp = temp +" " +list[i].ToString(); MessageBox.Show(temp); }
public static void UseParams2(params object[] list) ...{ string temp = ""; for (int i = 0; i < list.Length; i++) temp = temp + " " + list[i].ToString(); MessageBox.Show(temp); }
原则二:当希望方法返回多个值时,声明 out 方法非常有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有一个以上的 out 参数。
原则三:若要使用 out 参数,必须将参数作为 out 参数显式传递到方法。out 参数的值不会传递到 out 参数。
原则四:不必初始化作为 out 参数传递的变量,因为out 参数在进入方法(函数)时后清空自己,使自己变成一个干净的参数,也因为这个原因必须在方法返回之前为 out 参数赋值(只有地址没有值的参数是不能被。net接受的)。
原则五:属性不是变量,不能作为 out 参数传递。
原则六:如果两个方法的声明仅在 out 的使用方面不同,则会发生重载。不过,无法定义仅在 ref 和 out 方面不同的重载。例如,以下重载声明是有效的:
class MyClass { public void MyMethod(int i) {i = 10; } public void MyMethod(out int i) {i = 10; } } 而以下重载声明是无效的: class MyClass { public void MyMethod(out int i) {i = 10; } public void MyMethod(ref int i) {i = 10; } }
原则六:如果两种方法的声明仅在它们对 ref 的使用方面不同,则将出现重载。但是,无法定义仅在 ref 和 out 方面不同的重载。例如,以下重载声明是有效的:
class MyClass { public void MyMethod(int i) {i = 10; } public void MyMethod(ref int i) {i = 10; } } 但以下重载声明是无效的: class MyClass { public void MyMethod(out int i) {i = 10; } public void MyMethod(ref int i) {i = 10; } }
有关传递数组的信息,请参见使用 ref 和 out 传递数组。
示例
public static string TestOut(out string i) ...{ i = "out b"; return "return value"; }
public static void TestRef(ref string i) ...{ //改变参数 i = "ref b"; }