zoukankan      html  css  js  c++  java
  • out 和 ref 参数修饰符

    整理自MSDN

    out:

    out 关键字通过引用传递参数。这与 ref 关键字相似,只不过 ref 要求在传递之前初始化变量。若要使用 out 参数,方法定义和调用方法均必须显式使用 out 关键字。例如:

    class OutExample
    {
        static void Method(out int i)
        {
            i = 44;
        }
        static void Main()
        {
            int value;
            Method(out value);
            // value is now 44
        }
    }

    尽管作为 out 参数传递的变量无需在传递之前初始化,调用方法仍要求在方法返回之前赋值

    尽管 ref 和 out 关键字会导致不同的运行时行为,它们并不被视为编译时方法签名的一部分。因此,如果唯一的不同是一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,以下代码将不会编译:

    class CS0663_Example
    {
        // Compiler error CS0663: "Cannot define overloaded 
        // methods that differ only on ref and out".
        public void SampleMethod(out int i) { }
        public void SampleMethod(ref int i) { }
    }

    但是,如果一个方法采用 ref 或 out 参数,而另一个方法采用其他参数,则可以完成重载,如:
    class OutOverloadExample
    {
        public void SampleMethod(int i) { }
        public void SampleMethod(out int i) { i = 5; }
    }
    属性不是变量,因此不能作为 out 参数传递。

    ref:

    ref 关键字会导致参数通过引用传递,而不是通过值传递。 通过引用传递的效果是,对所调用方法中的参数进行的任何更改都反映在调用方法中。例如,如果调用方传递本地变量表达式或数组元素访问表达式,所调用方法会将对象替换为 ref 参数引用的对象,然后调用方的本地变量或数组元素将开始引用新对象。

    若要使用 ref 参数,方法定义和调用方法均必须显式使用 ref 关键字,如下面的示例所示。

    class RefExample
    {
        static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }
    
        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);
    
            // Output: 45
        }
    }
    

    传递到 ref 形参的实参必须先经过初始化,然后才能传递这与 out 形参不同,在传递之前,不需要显式初始化该形参的实参。有关详细信息,请参阅 out

    类的成员不能具有仅在 ref 和 out 方面不同的签名。如果类型的两个成员之间的唯一区别在于其中一个具有 ref 参数,而另一个具有 out 参数,则会发生编译错误。

  • 相关阅读:
    排序算法(二)插入排序---直接插入排序
    Shazam 是如何听音辨曲的?
    Android 读取<meta-data>元素的数据
    Android <uses-featureandroid:name="string">详解
    Android AsyncTask的用法
    Android ViewPager使用详解
    Git 使用教程(4)—— Git 常用命令集合
    Git 使用教程(3)
    Git 使用教程(2)
    Git 使用教程
  • 原文地址:https://www.cnblogs.com/wang-xiaohui/p/5311458.html
Copyright © 2011-2022 走看看