zoukankan      html  css  js  c++  java
  • C#使用out和ref传递数组参数

          闲来无聊拿着公司之前的asp.net项目看,重新激发了我学C#的冲动,哇咔咔~~~毕竟它太优雅了~

          人懒手不勤,脑子再好用都是白搭,现在就开始贴我自学的漫漫过程吧,给未来的自己感谢自己的理由!!

    今天说说ref和out    

      ref所传的参数必须由调用方明确赋值,被调用方可以对其进行修改;

      out所传的参数就不必由调用方明确赋值了.

      将这层意思应用到数组类型的参数上,也就是说,ref传递的数组必须是调用函数里已经初始化好的,而被调函数可对其进行某些元素的在赋值或者初始化.

      使用out传递数组就无所谓是不是已在主调函数中初始化好的了.

    贴个例子(取自C#编程指南):

    class TestOut
    {
        static void FillArray(out int[] arr)
        {
            // Initialize the array:
            arr = new int[5] { 1, 2, 3, 4, 5 };
        }
    
        static void Main()
        {
            int[] theArray; // Initialization is not required
    
            // Pass the array to the callee using out:
            FillArray(out theArray);
    
            // Display the array elements:
            System.Console.WriteLine("Array elements are:");
            for (int i = 0; i < theArray.Length; i++)
            {
                System.Console.Write(theArray[i] + " ");
            }
    
            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
        /* Output:
            Array elements are:
            1 2 3 4 5        
        */
    ***********************************************************************************************************************************************************
    class TestRef
    {
        static void FillArray(ref int[] arr)
        {
            // Create the array on demand:
            if (arr == null)
            {
                arr = new int[10];
            }
            // Fill the array:
            arr[0] = 1111;
            arr[4] = 5555;
        }
    
        static void Main()
        {
            // Initialize the array:
            int[] theArray = { 1, 2, 3, 4, 5 };
    
            // Pass the array using ref:
            FillArray(ref theArray);
    
            // Display the updated array:
            System.Console.WriteLine("Array elements are:");
            for (int i = 0; i < theArray.Length; i++)
            {
                System.Console.Write(theArray[i] + " ");
            }
    
            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
        /* Output:
            Array elements are:
            1111 2 3 4 5555
        */
    

     

     
  • 相关阅读:
    jQuery检测滚动条(scroll)是否到达底部
    sql group by
    hbm.xml 详解总结
    net.sf.json 时间格式的转化
    经典SQL语句大全
    HashTable
    in与exist , not in与not exist 的区别
    网页布局常用的一些命名规则和书写
    什么是SOA?
    sql之left join、right join、inner join的区别
  • 原文地址:https://www.cnblogs.com/liumumu2014/p/3785957.html
Copyright © 2011-2022 走看看