zoukankan      html  css  js  c++  java
  • C#基础之out,ref关键字

    1. out关键字会导致参数通过引用来传递。这与ref关键字类似,不同之处在于 ref要求变量必须在传递之前进行初始化。若要使用 out参数,方法定义和调用方法都必须显式使用 out关键字。当希望方法返回多个值时,声明 out方法很有用。使用 out参数的方法仍然可以将变量用作返回类型,但它还可以将一个或多个对象作为 out参数返回给调用方法。此示例使用 out在一个方法调用中返回三个变量。请注意,第三个参数所赋的值为 Null。这样便允许方法有选择地返回值.。

    class OutReturnExample

      {

      static void Method(out int i, out string s1, out string s2)

      {

      i = 44;

      s1 = "I've been returned";

      s2 = null;

      }

      static void Main()

      {

      int value;

      string str1, str2;

      Method(out value, out str1, out str2);

      // value is now 44

      // str1 is now "I've been returned"

      // str2 is (still) null;

      }

     }

    2.ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:

    class RefExample

    { static void Method(ref int i)

    { i = 44; }

       static void Main()

    {

    int val = 0;

    Method(ref val);

    // val is now 44

    }

    }

    传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。尽管 refout 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用out 参数,则无法重载这两个方法。

    ref和out两个参数的不同在于:

      1、ref传进去的参数必须在调用前初始化,out不必,即:

      int i;

      SomeMethod( ref i );//语法错误

      SomeMethod( out i );//通过

      2、ref传进去的参数在函数内部可以直接使用,而out不可:

      public void SomeMethod(ref int i)

      {

      int j=i;//通过

      //...

      }

      public void SomeMethod(out int i)

      {

      int j=i;//语法错误

      }

      3、ref传进去的参数在函数内部可以不被修改,但out必须在离开函数体前进行赋值。

    注:本文整理自网络!!!

  • 相关阅读:
    OSVERSIONINFOEX structure
    VS系列开发工具发展概述
    VS2008与QT4.6集成
    windows nt service 框架
    Rair
    如何在进程之间共享内核对象
    GOOGLE
    如何获取错误消息说明使用 FormatMessage API
    EnableDebugPriv;
    汇编语言资料
  • 原文地址:https://www.cnblogs.com/YuanSong/p/2599410.html
Copyright © 2011-2022 走看看