C#中关于out和ref的使用

来源:互联网 发布:圣象地板 知乎 编辑:程序博客网 时间:2024/06/05 12:47
        static void swap(ref int i1,ref int i2)        {            int temp = i1;            i1 = i2;            i2 = temp;        }        //使用时,通过ref声明为引用。        int i1 = 10, i2 = 20;        swap(ref i1, ref i2);        Console.WriteLine("i1={0},i2={1}", i1, i2);

1.

        static void IncAge(int age) //复制了age,函数内部改变的是age的副本        {            age++;        }



2.

ref用于内部对外部的值进行改变。

        //ref用于内部对外部的值进行改变。                static void IncAge( ref int refage)  //ref把age声明为一个引用,age必须先初始化        {            refage++;        }

3.

out用于内部对外部变量进行赋值,一般应用于函数有多个返回值的场景

        static void IncAge(out int outage)        {            outage = 30;        }            int outage; //不需要初始化,初始化也不起作用            String str = Console.ReadLine();            if (int.TryParse(str, out outage))            {                Console.WriteLine("转换成功,{0}", outage);            }            else            {                Console.WriteLine("转换失败,{0}", outage);            }



0 0