• ref & out


    ref & out - C#中的参数传递

      ref与out均指定函数参数按引用传递,惟一的不同是,ref传递的参数必须初始化,而out可以不用。

      ref与out无法作为重载的依据,即ref与out编译器认为一样。如下:

      

      但是ref函数与非ref函数是可以重载的,如下:

      

      To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example.

      

      A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref or out keyword.

    class PassingRefByVal 
    {
        static void Change(int[] pArray)
        {
            pArray[0] = 888;  // This change affects the original element.
            pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
            System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
        }
    
        static void Main() 
        {
            int[] arr = {1, 4, 5};
            System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);
    
            Change(arr);
            System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
        }
    }
    /* Output:
        Inside Main, before calling the method, the first element is: 1
        Inside the method, the first element is: -3
        Inside Main, after calling the method, the first element is: 888
    */
    View Code

    参考:

    1、http://msdn.microsoft.com/zh-cn/library/14akc2c7(VS.80).aspx

    2、http://msdn.microsoft.com/zh-cn/library/t3c3bfhx(v=vs.80).aspx

    3、http://msdn.microsoft.com/zh-cn/library/s6938f28.aspx

  • 相关阅读:
    dubbo 学习
    JSTL 实现 为Select赋多个值
    Spring MVC 单元测试Demo
    IDEA git commit push revert
    高并发处理
    Redis Expire TTL命令
    Redis 原子操作INCR
    Redis 安装
    慢日志查询
    angularJs 处理多选框(checkbox)
  • 原文地址:https://www.cnblogs.com/tekkaman/p/3800191.html
Copyright © 2020-2023  润新知