zoukankan      html  css  js  c++  java
  • out, ref 和 params 的区别和用法

    1. out 参数。

    如果你在一个方法中,返回多个相同类型的值,可以考虑返回一个数组。

    但是,如果返回多个不同类型的值,返回数组就不可取。这个时候可以考虑使用out参数。

    out参数就侧重于在一个方法中可以返回多个不同类型的值。

    static void Main(string[] args)
            {
                //调用
                int[] numbers = { 1, 2, 3, 4, 5 };
                int max;
                bool isFinished;
                Test(numbers, out max, out isFinished);
                Console.WriteLine(max);
                Console.WriteLine(isFinished);
                Console.ReadLine();
                // 输出结果为:max:5 isfinished: true
            }
    
            public static void Test(int[] nums, out int max, out bool isFinished)
            {
                //out 参数要求在method内部必须为其赋值
                max = nums[0];
                isFinished = false;
                for (int i = 0; i < nums.Length; i++)
                {
                    if (nums[i] > max)
                    {
                        max = nums[i];
                    }
                }
                isFinished = true;
            }

    Ref参数

    能够将一个变量带入一个方法中进行改变,改变完成后,再将改变后的值带出方法。不需要写返回值

    static void Main(string[] args)
            {
                //调用
                double[] numbers = new double[] { 1, 2, 3, 5.5 };
                double i = 0;
                MyAddOperation(numbers, ref i);
                Console.WriteLine("计算结果的2倍是:{0}", i * 2);
                Console.ReadLine();
                // 输出结果为:23
            }
    
            //引用参数方法声明
            public static void MyAddOperation(double[] numbers, ref double result)
            {
                result = 0;
                foreach (double num in numbers)
                    result += num;
                Console.WriteLine("计算结果是:{0}", result);
            }

    params 可变参数将实参列表中跟可变参数数组类型一致的元素都当做数组的元素去处理。

    params可变参数必须是形参列表中的最后一个元素。

            public void test2()
            {
                Test("name", 1,2,3);
            }
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="name"></param>
            /// <param name="score"></param>
            public void Test(string name, params int[] score)
            {
                var sum = 0;
                for (int i = 0; i < score.Length; i++)
                {
                    sum += score[i];
                }
            }
  • 相关阅读:
    MyEclipse 自带的TomCat 新增部署的时候不显示 Deploy Location
    No prohects are avaliable for deployment to this server
    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    Dom4j 对XMl解析 新手学习,欢迎高手指正
    电脑的技巧
    Browserify的基本使用
    bower的基本使用
    前端工程化--前端工程化技术栈
    前端工程化--架构说明
    前端工程化-前端工程化说明
  • 原文地址:https://www.cnblogs.com/TheMiao/p/9220408.html
Copyright © 2011-2022 走看看