zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# ref

c# ref
2023-09-11 14:16:46 时间

ref参数
能够将一个变量带入一个方法中进行改变,改变完成后,再讲改变后的值带出方法,
ref参数要求在方法外必须为其赋值,而方法内可以不赋值。
对比两个代码运行结果理解ref参数

using System;

namespace Ref参数
{
    class Program
    {
        static void Main(string[] args)
        {
            double salary = 5000;
            JiangJin(salary);
            Console.WriteLine(salary);//将此行代码中的salary改为s看看运行结果
            Console.ReadKey();
        }

        public static void JiangJin(double s)
        {
            s += 500;
        }

        public static void FaKuan(double s)
        {
            s -= 500;
        }
    }
}

using System;

namespace Ref练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用方法来交换两个int类型的变量
            int n1 = 10;
            int n2 = 20;
            /*int temp = n1;
            n1 = n2;
            n2 = temp;*/

            Test(ref n1, ref n2);
            Console.WriteLine(n1);
            Console.WriteLine(n2);
            Console.ReadKey();



            /*n1 = n1 - n2;
            n2 = n1 + n2;
            n1 = n2 - n1;*/  //结果 20 10
        }

        public static void Test(ref int n1,ref int n2)
        {
            int temp = n1;
            n1 = n2;
            n2 = temp;
        }
    }
}