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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值