码迷,mamicode.com
首页 > 其他好文 > 详细

ref、out 关键字

时间:2014-10-10 18:51:14      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   sp   div   

    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;
        }
    }

bubuko.com,布布扣

    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;
        }
    }

bubuko.com,布布扣

 如果把一个参数传递给方法,且这个方法的输入参数钱带有ref关键字,则改方法对变量所做的任何改变都会影响原始对象的值。

bubuko.com,布布扣
    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;
        }
    }
View Code

bubuko.com,布布扣

变量如果未赋初始值而是用肯定会报错,而是用Out关键字之后可以解决这一问题

ref、out 关键字

标签:style   blog   http   color   io   os   ar   sp   div   

原文地址:http://www.cnblogs.com/liuhuanping/p/4016343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!