c#---ref参数

员工基本工资为5000元,奖金方法+500元,调用该方法之后为什么工资还是5000元?

static void Main(string[] args)
        {
            double salary = 5000;
            jiangJin(salary);
            Console.WriteLine(salary);
            Console.ReadKey();
        }
public static void jiangJin(double salary) { salary += 500; }

5500的正确代码写法,是不是有点麻烦呢?

static void Main(string[] args)
        {
            double salary = 5000;
            double d = jiangJin(salary);
            Console.WriteLine(d);
            Console.ReadKey();
        }
public static double jiangJin(double salary) { salary += 500; return salary; }

ref参数:将变量带入一个方法中改变之后在带出方法

注意事项:

ref参数在方法外也就是调用方法之前必须为其赋值

 static void Main(string[] args)
        {
            double salary = 5000;
            jiangJin(ref salary);
            Console.WriteLine(salary);
            Console.ReadKey();
        }
        public static void jiangJin(ref double salary)
        {
            salary += 500;

        }

ref参数在变量交换中的示例

 static void Main(string[] args)
        {
            int n1 = 10;
            int n2 = 100;
            Program.Test(ref n1, ref n2);
            Console.WriteLine(n1);
            Console.WriteLine(n2);
            Console.ReadKey();
        }

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

 

posted @ 2019-04-18 14:20  _Huang95  阅读(8337)  评论(0编辑  收藏  举报