还不太理解ref、out参数的,进来瞧瞧

来源:互联网 发布:免费网管软件 编辑:程序博客网 时间:2024/05/16 18:41
Code:
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5.   
  6. namespace RefOut   
  7. {   
  8.     class Program   
  9.     {   
  10.      
  11.         static void Main(string[] args)   
  12.         {   
  13.             int age = 10;   
  14.             incAge(age);   
  15.             Console.WriteLine("在Main函数中age的值是{0}",age);//不会打印20,却还是打印出10   
  16.          //因为通过incAge函数传参 --是“值传递”,相当于把age变量的值“复制了一份”而已   
  17.          //尽管incAge函数中age值发生改变,但不会对main函数中的age产生影响,因为这两个age根本不是同一个变量   
  18.   
  19.             int score = 80;   
  20.             incScore(ref score);   
  21.             Console.WriteLine("在Main函数中score的值是{0}", score);//会打印出81   
  22.             //使用ref 关键字后,会传递变量的引用,当变量在外部发生改变时,Main函数中也会改变。   
  23.   
  24.             int i;   
  25.             InitVal(out i);//使用out参数  为了将变量在InitVal函数中赋初始值   
  26.             Console.WriteLine("在Main函数中i的值为{0}",i);//打印出100     
  27.             Console.ReadKey();   
  28.         }   
  29.         static void incAge(int age)    
  30.         {   
  31.             age +=10;  //age=age+10 =10+10   
  32.             Console.WriteLine("在incAge函数中age的值是{0}",age);//打印出 20   
  33.         }   
  34.         static void incScore(ref int score)    
  35.         {   
  36.             score++;   
  37.             Console.WriteLine("在incScore函数中score的值是{0}",score);//打印出81   
  38.         }   
  39.         static void InitVal(out int i)    
  40.         {   
  41.             i = 100;   
  42.             Console.WriteLine("在InitVal函数中i的值是{0}",i);//打印出100   
  43.         }   
  44.     }   
  45. }   

 

原创粉丝点击