zoukankan      html  css  js  c++  java
  • C# ref,out

    static void Main(string[] args)
    {
    int a = 1;
    int b = 2;
    string x = "x";
    string y = "y";

    Console.WriteLine("Main-->a:{0},b:{1}", a, b);
    Console.WriteLine("Main-->x:{0},y:{1}", x, y);

    TestInt(a, b);
    TestString(x, y);

    Console.WriteLine("Main-->a:{0},b:{1}", a, b);
    Console.WriteLine("Main-->x:{0},y:{1}", x, y);

    TestIntRef(ref a, ref b);
    TestStringRef(ref x, ref y);

    Console.WriteLine("Main-->a:{0},b:{1}", a, b);
    Console.WriteLine("Main-->x:{0},y:{1}", x, y);
    }

    public static void TestInt(int a, int b)
    {
    a = 10;
    b = 20;
    Console.WriteLine("TestInt-->a:{0},b:{1}", a, b);
    }

    public static void TestIntRef(ref int a, ref int b)
    {
    a = 100;
    b = 200;
    Console.WriteLine("TestIntRef-->a:{0},b:{1}", a, b);
    }

    public static void TestString(string x, string y)
    {
    x = "123x";
    y = "123y";
    Console.WriteLine("TestString-->x:{0},y:{1}", x, y);
    }

    public static void TestStringRef(ref string x, ref string y)
    {
    x = "ref:123x";
    y = "ref:123y";
    Console.WriteLine("TestStringRef-->x:{0},y:{1}", x, y);
    }
     

    Out:

    static void Main(string[] args)
    {
    int a;
    string x, y;
    TestOut(out a);
    Console.WriteLine(a);  //a等于101s
    }

    public static void TestOut(out int a)
    {
    a = 101;
    }

    总结:out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字

  • 相关阅读:
    Python中获取异常(Exception)信息
    Python 3.5 连接Mysql数据库(pymysql 方式)
    用命令查看Mysql中数据库、表的空间大小
    MySQLdb操作mysql的blob值
    mysql.connector操作mysql的blob值
    windows获取硬盘使用率等信息
    python操作系统环境变量
    git clone
    在Spring项目中使用Log4j记录日志
    org.apache.log4j.Logger详解
  • 原文地址:https://www.cnblogs.com/kelei12399/p/2316389.html
Copyright © 2011-2022 走看看