[对象和类型]5.引用传参和值传参:ref参数,out参数

Posted on 2009-09-26 12:44  Relax Active  阅读(380)  评论(0)    收藏  举报
 

Ref参数:

说明:方法的参数前带有ref关键字,则该方法对变量所做的任何改变都可以改变对象的值。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Demo8

{

    class Program

    {

        static void lay(int[] ints, ref int i)   //方法的参数i前带有ref关键字!

        {

            ints [0] = 10;

            i = 20;

        }

        static void Main(string[] args)

        {

            int i = 0;

            int[] ints = {1,2,3,4};

            Console.WriteLine("i =" +i);

            Console.WriteLine("ints[0] = " + ints[0]);

 

            lay(ints,ref i);      //方法的参数i有带有ref关键字,可改变原来对象的值!

            Console.WriteLine("i = " +i);

            Console.WriteLine("ints[0]=" + ints[0]);

        }

  

    }

}

 

out参数

说明:使用out关键字可以简化C#编译器坚持的输入参数的初始化。

示例代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Demo6

{

    class Program

    {

        static void function(out int i)

        {

            i = 100;

 

        }

        static void Main(string[] args)

        {

            int i;

            function(out i);

            Console.WriteLine("i ="+i);

        }

    }

}

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3