out和ref都使用引用传递将参数传入方法,out和ref的主要区别,ref使用时必须对传入的参数进行初始化,out对传入的参数在方法中必须赋值,否则会报错“控制离开方法之前必须对out参数赋值”
class Program { public static void Change0(out int a, out int b, out string
str) { a =1; b = 2; str = "str发生改变---Change0"; } public static void Change1(ref
int a, ref int b, ref string str) { a = 3; b = 4; str = "str发生改变---Change1"; }
static void Main(String[] args) { string str="123"; int a=0, b; Program.Change0(
out a, out b, out str); Console.WriteLine("a=" + a + " b=" + b + " str=" +
str); Program.Change1(ref a, ref b, ref str); Console.WriteLine("a=" + a + " b="
+ b +" str=" + str); Console.ReadKey(); } }
执行结果如下: