class ParameterTest { static void Main(string[] args) { int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); SomeFunction(ints,i); Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); Console.ReadKey(); } static void SomeFunction(int[] ints,int i) { ints[0] = 100; i = 100; } }
class ParameterTest { static void Main(string[] args) { int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); SomeFunction(ints,ref i); Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); Console.ReadKey(); } static void SomeFunction(int[] ints,ref int i) { ints[0] = 100; i = 100; } }
如果把一个参数传递给方法,且这个方法的输入参数钱带有ref关键字,则改方法对变量所做的任何改变都会影响原始对象的值。
class OutTest { static void Main(string[] args) { int i; SomeFunction(out i); Console.WriteLine(i); Console.ReadKey(); } static void SomeFunction(out int i) { i = 100; } }
变量如果未赋初始值而是用肯定会报错,而是用Out关键字之后可以解决这一问题
时间: 2024-10-11 00:30:11