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

    运行结果如下:

  • 相关阅读:
    Oracle 表空间查询
    FlaskAppBuilder 中文文档 markdown格式
    Springboot + Stomp + React 实现通过前后端通信
    Jmeter自动生成UUID
    Jmeter响应断言中,中文匹配失败问题解决
    IOS使用纯代码布局替换掉默认的storyboard
    MySQL在Windows上创建服务和删除服务
    IOS15上纯代码布局之导航控制器的导航条为透明的问题
    PHP编译FTP扩展
    ansible处理一些逻辑请求思路
  • 原文地址:https://www.cnblogs.com/zhoukaiwei/p/2245680.html
Copyright © 2011-2022 走看看