zoukankan      html  css  js  c++  java
  • C#参数传递的方式

    C#中与参数有关系的关键字有三个params、ref及out
    params

    The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

    params

    输出结果是
    1
    2
    3

    1
    a
    test

    10
    11
    12
    ref
    The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.

    • An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed.
    • Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument.
    • however, if one method takes a ref or out argument and the other uses neither,it is OK. 
    • Properties are not variables. They are actually methods, and therefore cannot be passed as ref parameters. 

    看下面的例子:

    Code

    Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not related; a method parameter can be modified by ref regardless of whether it is a value type or a reference type. Therefore, there is no boxing of a value type when it is passed by reference. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.

    reference(引用)的概念来源于C++

    out
    out与ref的不同之处在于:

    • variables passed as out arguments do not have to be initialized before being passed
    • the called method is required to assign a value before the method returns.

    使用ref和out传递数组
    与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由被调用方为其赋值。例如:

    static void TestMethod1(out int[] arr)
    {
        arr 
    = new int[10];   // definite assignment of arr
    }

    与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:

    static void TestMethod2(ref int[] arr)
    {
        arr 
    = new int[10];   // arr initialized to a different array
    }

    传递数组时,ref和out的使用并没有特殊之处。

  • 相关阅读:
    【次大gcd】#uoj #48. 【UR #3】核聚变反应强度
    1591:数字计数
    数位DP模板
    1588:数字游戏
    [NOIP 2017普及组 No.1] 成绩
    [NOIP 2017普及组 No.3] 棋盘
    Apache(httpd)实现反向代理
    注册阿里云域名
    SSH常用命令
    Linux yum 安装Java和MySQL
  • 原文地址:https://www.cnblogs.com/whyandinside/p/1562079.html
Copyright © 2011-2022 走看看