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

    一、使用ref参数传递数组

    数组类型的ref参数必须由调用方明确赋值。因此,接受方不需要明确赋值。接受方数组类型的ref参数能够修改调用方数组类型的结果。可以将接受方的数组赋以null值,或将其初始化为另一个数组。请阅读引用型参数。

    示例:

    在调用方法(Main方法)中初始化数组array,并使用ref参数将其传递给theArray方法。在theArray方法中更新某些数组元素,然后将数组元素返回调用方并显示出来。
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Test
    {
        class Program
        {
            static void theArray(ref int[] arr) // 接受方不需要明确赋值
            {
                if (arr == null)       // 根据需要创建一个新的数组(不是必须的)
                {
                    arr = new int[10]; // 将数组赋以null值,或将其初始化为另一个数组
                }
                arr[0] = 11;
                arr[4] = 55;
            }
            static void Main(string[] args)
            {
                // C#使用ref参数传递数组-www.baike369.com
                int[] array = { 1, 2, 3, 4, 5 };
                theArray(ref array);            // 使用ref传递数组,调用方明确赋值
                Console.Write("数组元素为:");
                for (int i = 0; i < array.Length; i++)
                {
                    Console.Write(array[i] + " ");
                }
                Console.ReadLine();
            }
        }
    }

    运行结果:
     
    数组元素为:11 2 3 4 55

    二、使用out参数传递数组
    被调用方在使用数组类型的out参数时必须为其赋值。请阅读输出参数。

    示例:

    在调用方方法(Main方法)中声明数组array,并在theArray方法中初始化此数组。然后将数组元素返回到调用方并显示出来。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Test
    {
        class Program
        {
            static void theArray(out int[] arr)
            {
                arr = new int[]{0,2,4,6,8}; // 必须赋值
            }
            static void Main(string[] args)
            {
                int[] array;
                theArray(out array);           // 传递数组给调用方
                Console.Write("数组元素为:"); // 显示数组元素
                for (int i = 0; i < array.Length; i++)
                {
                    Console.Write(array[i] + " ");
                }
                Console.ReadLine();
            }
        }
    }

    运行结果:

    数组元素为:0 2 4 6 8

  • 相关阅读:
    Windows Install Twisted 安装Twisted
    raspberry pi随图形界面开机启动 被执行两次的问题
    将任意程序(如.bat文件)作为Windows服务运行
    xampp无法打开phpmyadmin解决方案
    python的subprocess无法进行通信(无法通过管道输入数据)的问题解决
    关于接地/共地
    树莓派字体安装
    windows 不能在本地计算机启动apache2 的解决方法(不是修改端口)
    5 November in 614
    模拟退火算法
  • 原文地址:https://www.cnblogs.com/melao2006/p/4239191.html
Copyright © 2011-2022 走看看