zoukankan      html  css  js  c++  java
  • 关于数组传递以及ref,out的例子

    数组传递,ref与out的区别是,out可以先不初始化,等传递到调用方法后,再初始化。

    ref传递,会影响数组原始值。

    下面是一个例子:

            static void Main(string[] args)
    {
    int[] firstArray = { 1, 2, 3 };
    int[] firstArrayCopy = firstArray;
    Console.WriteLine("Test passing firstArray reference by
    value");
    Console.WriteLine("\nContents of firstArray before calling
    FirstDouble:\n\t");
    for (int i = 0; i < firstArray.Length; i++)
    Console.Write("{0} ", firstArray[i]);
    FirstDouble(firstArray);
    Console.WriteLine("\nContents of firstArray after calling
    FirstDouble:\n\t");
    for (int i = 0; i < firstArray.Length; i++)
    Console.Write("{0} ", firstArray[i]);
    if (firstArray == firstArrayCopy)
    Console.WriteLine("\n\nThe references refer to the
    same array");
    else
    Console.WriteLine("\n\nThe references refer to the
    different array");

    int[] secondArray = { 1, 2, 3 };
    int[] secondArrayCopy = secondArray;
    Console.WriteLine("\nTest passing secondArray reference
    by reference");
    Console.WriteLine("\nContents of secondArray before
    calling SecondDouble:\n\t");
    for (int i = 0; i < secondArray.Length; i++)
    Console.Write("{0} ", secondArray[i]);
    SecondDouble(ref secondArray);
    Console.WriteLine("\nContents of secondArray after calling
    SecondDouble:\n\t");
    for (int i = 0; i < secondArray.Length; i++)
    Console.Write("{0} ", secondArray[i]);
    if (secondArray == secondArrayCopy)
    Console.WriteLine("\n\nThe references refer to the
    same array");
    else
    Console.WriteLine("\n\nThe references refer to the
    different array");
    }

    private static void FirstDouble(int[] array)
    {
    for (int i = 0; i < array.Length; i++)
    array[i] *= 2;
    array = new int[] { 11, 12, 13 };
    }

    private static void SecondDouble(ref int[] array)
    {
    for (int i = 0; i < array.Length; i++)
    array[i] *= 2;
    array = new int[] { 11, 12, 13 };
    }

    运行结果如下:

  • 相关阅读:
    [zz] 从VMM中终止GUEST OS中运行进程
    [zz]Linux流量监控工具 – iftop (最全面的iftop教程)
    [zz]Ubuntu终端下Nethogs网络流量监控工具
    AtomicBoolean运用
    JDK中的URLConnection参数详解
    java读取文本文件数据
    tomcat时区设置
    java的upload
    java复习(set 、list、map)
    NIO学习笔记1
  • 原文地址:https://www.cnblogs.com/zhoukaiwei/p/2245680.html
Copyright © 2011-2022 走看看