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 };
    }

    运行结果如下:

  • 相关阅读:
    msgs no .h file
    我们为之奋斗过的C#之---简单的库存管理系统
    我们为之奋斗过的C#-----C#的一个简单理解
    套接字之sendto系统调用
    套接字之msghdr结构
    套接字之select系统调用
    套接字之close系统调用
    TCP之listen&backlog
    套接字之相关系统调用的调用流程
    套接字之shutdown系统调用
  • 原文地址:https://www.cnblogs.com/zhoukaiwei/p/2245680.html
Copyright © 2011-2022 走看看