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

原文地址:https://www.cnblogs.com/melao2006/p/4239191.html