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的使用并没有特殊之处。

  • 相关阅读:
    设计模式 ( 十七) 状态模式State(对象行为型)
    设计模式 ( 十六 ) 观察者模式Observer(对象行为型)
    设计模式 ( 十五 ) 中介者模式Mediator(对象行为型)
    设计模式 ( 十四 ) 迭代器模式Iterator(对象行为型)
    设计模式 ( 十三 ) 命令模式Command(对象行为型)
    设计模式(十一)代理模式Proxy(结构型)
    设计模式(十)享元模式Flyweight(结构型)
    开源项目
    C#中的Marshal
    给枚举加上Description,必要时,可以直接获取枚举类型代表的中文
  • 原文地址:https://www.cnblogs.com/whyandinside/p/1562079.html
Copyright © 2011-2022 走看看