zoukankan      html  css  js  c++  java
  • C#中ref和out的使用小结

    ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。

      使用ref前必须对变量赋值,out不用。

      out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。

      区别可以参看下面的代码:
    using System;
    class TestApp
    {
     
    static void outTest(out int x, out int y)
     {
    //离开这个函数前,必须对x和y赋值,否则会报错。 
      
    //y = x; 
      
    //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行 
      x = 1;
      y 
    = 2;
     }
     
    static void refTest(ref int x, ref int y)
     { 
      x 
    = 1;
      y 
    = x;
     }
     
    public static void Main()
     {
      
    //out test
      int a,b;
      
    //out使用前,变量可以不赋值
      outTest(out a, out b);
      Console.WriteLine(
    "a=;b=",a,b);
      
    int c=11,d=22;
      outTest(
    out c, out d);
      Console.WriteLine(
    "c=;d=",c,d);

      
    //ref test
      int m,n;
      
    //refTest(ref m, ref n); 
      
    //上面这行会出错,ref使用前,变量必须赋值

      
    int o=11,p=22;
      refTest(
    ref o, ref p);
      Console.WriteLine(
    "o=;p=",o,p);
     }
    }
  • 相关阅读:
    LVM 扩容硬盘笔记
    jupyter notebook 远程访问
    samba 配置文件详解
    linux 网络挂载 windows 共享文件夹
    cmder 与 win10 wsl ( 当前目录打开wsl)
    vscode for latex
    Python 使用代理
    Python Signal(信号) 异步系统事件
    centos7 install magento
    lua笔记
  • 原文地址:https://www.cnblogs.com/wantingqiang/p/1524379.html
Copyright © 2011-2022 走看看