C#中方法中 ref 和 out的使用

案例1:

 static void Main()
        {
            int[] ary = { 12, 13, 103, 10003 };
            int numLargerThan10,numLargerThan100,numLargerThan1000 ;
            Proc(ary, out numLargerThan10, out numLargerThan100, out numLargerThan1000);
            Console.WriteLine("有{0}个数大于10,有{1}个数大于100,有{2}个数大于1000",numLargerThan10,numLargerThan100,numLargerThan1000);
            Console.Read();
        }
 
        static void Proc(int[] ary, out int numLargerThan10, out int numLargerThan100, out int numLargerThan1000)
        {
            numLargerThan10 = 0;
            numLargerThan100 = 0;
            numLargerThan1000 = 0;
            foreach (var a in ary)
            {
                if (a > 1000)
                    numLargerThan1000++;
                else if (a > 100)
                    numLargerThan100++;
                else if (a > 10)
                    numLargerThan10++;
            }
        }

输出结果:
有2个数大于10,有1个数大于100,有1个数大于1000

案例2:

class Program   
   {   
       //使用out后必须对变量赋值   
       public void TestOut(out int x, out int y)   
       {   
           x = 1;   
           y = 2;   
       }   
       //此时传进来的值分别为x1:10,y1:11,输出之后的x1的值为2   
   
       public void TestRef(ref int x, ref int y)   
       {   
           //引用剪剪那句话传进来的是猪,出来的可能是头牛(很精辟!)   
           x = 2;   
               
       }   
       static void Main(string[] args)   
       {   
           int x;   
           int y;   
           Program P1 = new Program();   
           P1.TestOut(out x,out y);   
           Console.WriteLine("x={0},y={1}", x, y);   
           //在使用之前ref必须对变量赋值   
           int x1 = 10;   
           int Y1 = 11;   
           P1.TestRef(ref x1,ref Y1);   
           Console.WriteLine("x1={0},y1={1}", x1, Y1);   
       }   
   }  

输出结果:

x=1,y=2
x1=2,y1=11

 
原文地址:https://www.cnblogs.com/zyh1994/p/6128146.html