• 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;
            }
  • 相关阅读:
    python:返回函数,闭包
    对象的行为和数组
    类、对象和包
    Java语言中的程序流程控制
    初识Java,Java语言概述
    有限广播地址与直接广播地址
    H3C模拟器HCL注意事项
    HDLC协议
    NETBIOS的作用
    HP DL380G7 RAID配置
  • 原文地址:https://www.cnblogs.com/huangxuQaQ/p/10729367.html
Copyright © 2020-2023  润新知